-
Notifications
You must be signed in to change notification settings - Fork 38
-
While Loop
Structure:
while condition do put your job here end
Example:
while 1 == 1 do print (“I will run forever”) end
-
If-else Statement
Structure:
if condition then job end
if x == 0 then print (“Why am I nil?”) elseif x == 1 then print (“Did you flip my bit?”) else print (“I knew you hate binary. :/ ”) end
-
Functions
Structure:
function name(variables) code(do something) end
function sayHello() local pocket = true print (“Hello Pockets!”) if not pockets then print (“Who are you?”) end end
-
Require
Requiring files in
lua
is same as using class inJava
andPython
. When yourequire
some files all thefunctions
as well asvariables
will be accessible in the current file. Let's have a look.$ ls time.lua main1.lua main2.lua $
There are three files in the same directory. Let's see what two of those files have and how to reuse the codes in other files.
time.lua
local time = 10 function printTime() print("The current time is : " .. time) end function setTime(t) time = t end function getTime(t) return time end
Now let's import
time.lua
inmain.lua
. There are several ways to import files. Here are few examples. Please feel free to do some googling.main1.lua
require("time.lua") print("Main function running...") time.printTime() time.setTime(20) print("The new time is :" .. time.getTime())
main2.lua
Fun = require("time.lua") print("Main function running...") Fun.printTime() Fun.setTime(20) print("The new time is :" .. Fun.getTime())
As you can see, both
main1.lua
andmain2.lua
will do the same work. The only difference being the way of importing other files. These two ways ofrequiring
files resemble to sort ofstatic
andnon-static
content in Java. If you require byFile=require('file1.lua')
, you useFile
to access functions and if you just dorequire('file1.lua')
then you can usefile1.functionName()
to access functions. -
Other basics in Lua
local x = 5 local x = 3 if x == y then print("X is equal to y") end if x ~= y then print("x is not equal to y") end local b = true print("b is " .. toString(true)) --This prints 'b is true' local c = not b print("c is " .. toString(true)) --This prints 'c is false' -- Array -- local arr = {} arr[0] = “Hook” arr[1] = “Pocket” print("I am " .. arr[0]) --This prints: 'I am Hook' --Length of array print("Total length of this array is = " .. toString(#arr)) --Prints: 'Total length of this array is = 2' local arr1 = {} arr1[“robot”] = “Hook” arr1[“platform”] = “Nao" arr1["company"] = "Aldebaran" print("I am " .. arr1["robot"]) --This prints: 'I am Hook' print("I am in " .. arr1.platform .. " platform") --This prints: 'I am in Nao platform' -- Commenting: "--" sign infront of line will make it a comment -- This is a comment -- concatenation (Adding two strings): ".." characters concatenate two strings print(“Add me to “ .. var)