Jump to content
Jopa

Lua (programming language)

Recommended Posts

Example code

The classic  hello world program can be written as follows:

 

 

print("Hello World!")
 
Comments use the following syntax, similar to that of Ada, Eiffel, SOL and VHDL:

 

 

-- A comment in Lua starts with a double-hyphen and runs to the end of the line.
--[[ Multi-line strings & comments
are adorned with double square brackets. ]]
--[=[ Comments like this can have other --[[comments]] nested. ]=]
 
The factorial function is implemented as a recursive function in this example:

 

 

function factorial(n)
if n == 0 then
    return 1
 else
    return n * factorial(n - 1)
 end
end
 
Loops

Lua has four types of loops: the while loop, the repeat loop, the for loop, and the generic for loop. (The local variables defined are to simply make the program complete. User variables are expected to be the normal input parameters for these functions.)

The while loop has the syntax:

 

 

while condition do
      --Statements
end
 
The repeat loop:

 

local cond = false
repeat
  --Statements
until cond
 
executes the loop body at least once, and would keep looping until cond becomes true.

 

The for loop:

 

for index = 1,5 do
      print(index)
end
 
would repeat the loop body 5 times, outputting the numbers 1 through 5 inclusive.

 

Another form of the for loop is:

 

local start,finish,delta = 10,1,-1 --delta may be negative, allowing the for loop to count down or up.
for index = start,finish,delta do
    print(index)
end
 
The generic for loop:

 

for key,value in pairs(_G) do
    print(key,value)
end
 
would iterate over the table _G using the standard iterator function pairs, until it returns nil.

 

 

Functions

Lua’s treatment of functions as first-class values is shown in the following example, where the print function’s behavior is modified:

 

do
local oldprint = print -- Store current print function as oldprint
function print(s) -- Redefine print function, the usual print function can still be used
  if s == "foo" then
    oldprint("bar")
  else
     oldprint(s)
     end
   end
 end
 
Any future calls to print will now be routed through the new function, and because of Lua’s lexical scoping, the old print function will only be accessible by the new, modified print.

 

Lua also supports closures, as demonstrated below:

 

function addto(x)
-- Return a new function that adds x to the argument
return function(y)
  --[[ When we refer to the variable x, which is outside of the current
     scope and whose lifetime is longer than that of this anonymous
     function, Lua creates a closure.]]
  return x + y
 end
end
fourplus = addto(4)
print(fourplus(3)) -- Prints 7
 
A new closure for the variable x is created every time addto is called, so that the anonymous function returned will always access its own x parameter. The closure is managed by Lua’s garbage collector, just like any other object.

 

Tables are created using the {} constructor syntax:

 

a_table = {} -- Creates a new, empty table
 
Tables are always passed by reference:

 

a_table = {x = 10} -- Creates a new table, with one entry mapping "x" to the number 10.
print(a_table["x"]) -- Prints the value associated with the string key, in this case 10.
b_table = a_table
b_table["x"] = 20 -- The value in the table has been changed to 20.
print(b_table["x"]) -- Prints 20.
print(a_table["x"]) -- Also prints 20, because a_table and b_table both refer to the same table.
 
We can insert/remove values/indexes from tables, as well.

 

local myTable={"a","b"}
table.insert(myTable,"c") --print(unpack(myTable)) --> a b c
table.remove(myTable,2) --print(unpack(myTable)) --> a c
 
As record

A table is often used as sructure (or record) by using strings as keys. Because such use is very common, Lua features a special syntax for accessing such fields. Example:

 

point = { x = 10, y = 20 } -- Create new table
print(point["x"]) -- Prints 10
print(point.x) -- Has exactly the same meaning as line above
 
As namespace

By using a table to store related functions, it can act as a namespace.

 

Point = {}

Point.new = function(x, y)
  return {x = x, y = y}
end

Point.set_x = function(point, x)
  point.x = x
end
 
As array

By using a numerical key, the table resembles an arraydata tipe. Lua arrays are 1-based: the first index is 1 rather than 0 as it is for many other programming languages (though an explicit index of 0 is allowed).

A simple array of strings:

 

array = { "a", "b", "c", "d" }             -- Indices are assigned automatically.
print(array[2])                            -- Prints "b". Automatic indexing in Lua starts at 1.
print(#array)                              -- Prints 4. # is the length operator for tables and strings.
array[0] = "z"                             -- Zero is a legal index.
print(#array)                              -- Still prints 4, as Lua arrays are 1-based.
 
The length of a table t is defined to be any integer index n such that t[n] is not nil and t[n+1] is nil; moreover, if t[1] is nil, n can be zero. For a regular array, with non-nil values from 1 to a given n, its length is exactly that n, the index of its last value. If the array has "holes" (that is, nil values between other non-nil values), then #t can be any of the indices that directly precedes a nil value (that is, it may consider any such nil value as the end of the array).

 

An array of objects:

 

function Point(x, y)                            -- "Point" object constructor
return { x = x, y = y }                         -- Creates and returns a new object (table)
end
array = { Point(10, 20), Point(30, 40), Point(50, 60) }         -- Creates array of points
print(array[2].y)                                               -- Prints 40
 
Using a hash map to emulate an array normally is slower than using an actual array; however, Lua tables are optimized for use as arrays to help avoid this issue.

 

Metatables

Extensible semantics is a key feature of Lua, and the metatable concept allows Lua’s tables to be customized in powerful ways.

 

 

fibs = { 1, 1 }                                  -- Initial values for fibs[1] and fibs[2].
setmetatable(fibs, {
__index = function(name, n)                      -- Call this function if fibs[n] does not exist.
name[n] = name[n - 1] + name[n - 2]              -- Calculate and memoize fibs[n].
return name[n]
 end
})
 
Another example, with the __call metamethod to create an Object Oriented Programming feel:

 

newPerson = {} -- Creates a new table called 'newPerson'.

setmetatable(newPerson, {
__call = function(table,name,age)           -- Turns the newPerson table into a functable.
local person = {Name = name, Age = age}     -- Creates a local variable which has all the properties of the person you create later on.  
return person -- Returns the table person so when you create it, it will set the variables in the table person.
 end
})

Bill = newPerson("Bill Raizer", 21)         -- Creates a new person.
print(Bill.Name, Bill.Age)                  -- Prints the name and age.
 
Creating a basic vector object:

 

Vector = {}                                -- Create a table to hold the class methods
function Vector:new(x, y, z)               -- The constructor
local object = { x = x, y = y, z = z }
setmetatable(object, { __index = Vector }) -- Inheritance
return object
end
function Vector:magnitude()               -- Another member function
   -- Reference the implicit object using self
return math.sqrt(self.x^2 + self.y^2 + self.z^2)
end

vec = Vector:new(0, 1, 0)                 -- Create a vector
print(vec:magnitude())                    -- Call a member function using ":" (output: 1)
print(vec.x)                              -- Access a member variable using "." (output: 0)
 
This example is the bytecode listing of the factorial function defined above (as shown by the luac 5.1 compiler):

 

 

 

function <factorial.lua:1,6> (10 instructions, 40 bytes at 003D5818)
1 param, 3 slots, 0 upvalues, 1 local, 3 constants, 0 functions
        1       [2]     EQ              0 0 -1  ; - 0
        2       [2]     JMP             2       ; to 5
        3       [3]     LOADK           1 -2    ; 1
        4       [3]     RETURN          1 2
        5       [5]     GETGLOBAL       1 -3    ; factorial
        6       [5]     SUB             2 0 -2  ; - 1
        7       [5]     CALL            1 2 2
        8       [5]     MUL             1 0 1
        9       [5]     RETURN          1 2
        10      [6]     RETURN          0 1
 
 
Example

Here is an example of calling a Lua function from C:

 

#include <stdio.h>
#include <stdlib.h>
#include <lua.h>
#include <lauxlib.h>

int main()
{
   lua_State *L = luaL_newstate();
   if (luaL_dostring(L, "function foo (x,y) return x+y end")) exit(1);
   lua_getglobal(L, "foo");
   lua_pushinteger(L, 5);
   lua_pushinteger(L, 3);
   lua_call(L, 2, 1);
   printf("Result: %d\n", lua_tointeger(L, -1));
   lua_close(L);
   return 0;
}

 
Running this example gives:

 

 

$ gcc -o example -llua example.c
$ ./example
Result: 8
 
 
Edited by Fearless Staff

Share this post


Link to post
Share on other sites

well, you simply copied the text and source code from wikipedia. without naming the source it is looking like YOU created this by your own. even in wikipedia you can find source links. just my 2 cents

  • Like 1

Share this post


Link to post
Share on other sites

No problem, I understand what you mean, I have something in the Cod so I became tutoril, all of which become by not becoming a source from where but if someone asks me I will gladly explain where it has to look ok :)

Share this post


Link to post
Share on other sites

No problem, I understand what you mean, I have something in the Cod so I became tutoril, all of which become by not becoming a source from where but if someone asks me I will gladly explain where it has to look ok :)

No.

 

The difference is that when you write your own text, you don't need to give the source since it is yourself. If you copy it (and basically, everything more than a single trivial line), you give the source. You don't wait until you're asked, you do it beforehand. Don't pretend to write it your own. The fact that "nobody" does it either is no excuse for that.

 

 

And I'll say it once: This occurs with other tutorials of you as well and is imho unacceptable.

  • Like 1

Share this post


Link to post
Share on other sites

Comments - Keywords

 

In every programming language so called comments are existing. In large scripts they can be used for a better overview. Other people will have a better understanding of you have done in your script.


Every programming language has its own characters, who tell the interpreter that the following (comment) is not really necessary. As we are learning LUA, here it is for LUA:

 

 
 

 

  -- everything behind this, wil not been red by the interpreter
 

(but it is only valid for this line)

 

 

If we want to create a comment of more than one line, we use -–[[ for the beginning and ]] for finishing the comment. We remind of the string: it is a similar way, but there we do not use the two hyphen.




Another convenient application for comments is, if we do not want to execute a special part of our script. Then we make an according comment for these lines, before deleting them or using them in our script.


Let us create a comment at the editor. You see, that the line is turning green. Good to know. ;)
 

 

Keywords

 

We already have learned that some words are reserved. Keywords are reserved as well and wvery programming language has its own. Following please find the keywords at LUA:

 


    and     break   do    else       elseif
    
    end     false   for   function   if
    
    in      local   nil   not        or
    
    repeat  return  then  true       until     while

 

 

Enter these words in the Editor. Then you will see, that the editor knows them as keywords and turns them blue. This is also very convenient for the overview.


local function and end we already have learned as well.



Now we got a little bit curios and we try to enter numbers and strings as well in the editor. If their color will also change?

 

Like every programming language as well, LUA also have operators for concatenating parameter or variables. There are arithmetic, relational and logical operators, which can be combined with different data types. For sure, all operators in LUA need two parameters or variables to compare. With the exception of minus '-' as negation of a number and the reserved word 'not'.
Comparisons are used very often. Is something equal, bigger or smaller than etc.

 

The result of a comparison is either true or false.

 

Operator Description Example Result == left side equal to the right side? "Willi" == "willi" false ~= left side not equal to the right side? "Willi" ~= "willi" true < left side smaller than the right side? 2 < 3 true > left side bigger than the right side? 2 > 3 false <= left side smaller or equal to right side? 2 <= 3 true >= left side bigger or equal to right side? 2 >= 3 false

 

 

There we have the two ==. They are used together as operator for comparison.
Those operators are checking a condition and as result they return true or false.

We will need these operators very often by programming in LUA so we do not need have to learn them in detail. Furthermore, they are almost self-explanatory.

As mentioned above there we have the word "not". What is it about? With this question we come to the logical operators.

 

Logical operators

 

LUA knows following logical operators

 

 andor and not

 

and or
With 'and' and 'or' we can combine conditions (as shown above)

The result of such a combination will be true or false as well.

That means:
if condition1 and condition2 have to be fulfiled then
result = condition1 and condition2
We use following variables

 

willyIsDrunken = true
    grandmaIsBad = false
    WilliesWifeIsBad = true
Know we combine

 

 willyIsDrunken and grandmaIsBad --> false

 

 

if condition1 or condition2 have to be fulfiled then:
result = condition1 or condition2
willyIsDrunken or grandmaIsBad --> true

We also can use 'and' and 'or' together with 'not' (see below).

At this moment this would go beyond the scope of this chapter. We will talk about this later on.

 

 

not
not is simply a negation of a condition. It will be inverted. True becomes false and false becomes true.
e.g. (5 == 5) the result is true. At the condition
not (5==5) we get false as result.

There are a lot of more applications for this but I do not know if need them right at this moment. As mentioned before and before.....we get to it later on.

Something for our editor:

 

          print (5==4)  --> false in the output window
        print (5==5)  --> true in the output window

 

(press the arrow or F5 or Run - Run Script)

 

 

Already learned a lot and will do an exercise with the help of our editor. One advantage is, that we will get more and more familiar with the editor. Another advantage is that we can varify what we have learned until now and proof that we have understood. Practice makes perfect. The following chapters will become more difficult. If we have struggling with these things later on it would become at least very difficult to understand new things about LUA.
 

Therefore, have a break and exercise :):P

 

 

 

Share this post


Link to post
Share on other sites

Again I doubt you've written that yourself.

 

 

And with doubt I mean: know for 99.99% sure. Unless you've written it and posted it at some other location as well.

Share this post


Link to post
Share on other sites

link

 

Copying of any content of this site (text or graphics) is not allowed, excepted any source code shown in this tutorial. See also: ....Disclaimer
Copyright © Robert Schmitz 2006

Share this post


Link to post
Share on other sites

Okay guys, this is what I use every day in my work, if you do not  like this do not comment on,

I just want people to get closer to see what it is and also recall. :)

 

P.S. after all, they could all treated as such am I right???

Edited by Jopa

Share this post


Link to post
Share on other sites

I love it how you don't read.

 

 

So because you may have missed it, I quote myself:

 

 

No.

 

The difference is that when you write your own text, you don't need to give the source since it is yourself. If you copy it (and basically, everything more than a single trivial line), you give the source. You don't wait until you're asked, you do it beforehand. Don't pretend to write it your own. The fact that "nobody" does it either is no excuse for that.

 

 

And I'll say it once: This occurs with other tutorials of you as well and is imho unacceptable.

Share this post


Link to post
Share on other sites

this has nothing to do with "like" or "dislike". the fact is, you have copied something without naming the source.

 

 

Edit: you should be able to write your "own" tutorial if you are working with it every day.

Share this post


Link to post
Share on other sites

No way to put my work than that because I live of my work :)

 

 

 

I love it how you don't read. rolf  Listen, if you have some negative intentions will not fail you, please do not take me for no reason condemned with such sentences, thank you

Share this post


Link to post
Share on other sites

They are talking about you not putting down your SOURCES, which is plagiarism:

 

 

Plagiarism is the "wrongful appropriation" and "purloining and publication" of another author's "language, thoughts, ideas, or expressions," and the representation of them as one's own original work.

 

=> Hard way to say: don't copy somebodies writing without giving credit / mentioning your source

 

Source: click

Share this post


Link to post
Share on other sites

No way to put my work than that because I live of my work :)

 

 

 

I love it how you don't read. rolf  Listen, if you have some negative intentions will not fail you, please do not take me for no reason condemned with such sentences, thank you

 

 

I'm not saying that you are not allowed to post it, feel free (although a link would suffice). But I am saying that you should give credits where credit's due, as we all do. But you don't. That says so much over your character that I do not feel guilty in any way about stating anything about your (in)ability to read. More precisely, you should already have been able to understand that based on every single post other than yours in this topic.

  • Like 1

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×

Important Information

By using this site, you agree to our Terms of Use.