0% found this document useful (0 votes)
27 views8 pages

Lua Parancsok

Uploaded by

ctm Tpa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views8 pages

Lua Parancsok

Uploaded by

ctm Tpa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

ALAPOK

KOMMENTEK

 Egysoros komment:
o -- This is a single-line comment
 Többsoros kommenttömb:
o --[[ This is a multi-line
o comment ]]
 Soron belüli komment tömb:
o t = {1, 2, --[[in-line block comment]] 3}
 Kommenttömb, amely tartalmaz: ']]' :
o --[=[ Block comment that contains "]]". ]=]

VÁLTOZÓK & SCOPE (HATÓKÖR, INTERVALLUM)

 Globális változók: varName = value


 Helyi változók: local varName = value
 Példa:
 x = 1 -- global variable
 local function equal(z)
 ...
 local x = x -- local x = global x
 ...
end

ADATTÍPUSOK

 Nulla (Nil): nil


 Logikai (Boolean): true, false
 Szám (Number): 123, 4.56
 Szövegtípus (String): "Hello", 'World'
 Függvény (Function): function() end
 Lista (Table): {} (sorrendekhez, szótárakhoz, elemekhez használjuk)
 Thread: coroutine functions
 Userdata: custom C data types

OPERÁTOROK
SZÁMTANI OPERÁTOROK

 Összeadás: `x + y'
 Substract: x - y
 Multiply: x * y
 Divide: x / y
 Integer divide: x // y
 Reminder of Division: x % y
 Exponentiate: x^y
RELÁCIÓSJEL OPERÁTOROK

 Is a equal to b?: a == b
 Is a not equal to b?: a ~= b
 a is less than b?: a < b
 a is less than or equal b?: a <= b
 a is greater than or equal a?: a > b
 a is greater than or equal a?: a >= b Returns a boolean.

LOGIKAI OPERÁTOROK

 not a:It negates the boolean value of a.


 a and b: This operator returns a if a is false; otherwise, it returns b. It is
used to check if both conditions a and b are true.
 a or b: This operator returns a if a is true; otherwise, it returns b. It is
useful for selecting the first true value between a and b.

BITWISE OPERATORS

 Bitwise AND:
o x & y (Lua 5.3, 5.4)
o bit32.band(x, y) (Lua 5.2)
 Bitwise OR:
o x | y (Lua 5.3, 5.4)
o bit32.bor (x, y) (Lua 5.2)
 Bitwise XOR:
o x ~ y (Lua 5.3, 5.4)
o bit32.bxor(x, y) (Lua 5.2)
 Bitwise NOT:
o ~x (Lua 5.3, 5.4)
o bit32.bnot(x) (Lua 5.2)
 Shift:
o x << y (Lua 5.3, 5.4)
o bit32.lshift(x, y) (Lua 5.2)
o x >> y (Lua 5.3, 5.4)
o bit32.rshift(x, y) (Lua 5.2)

OTHER OPERATORS

 Returns strings or numbers a and b concatenated together into a new


string: a .. b
 Returns the length of value v: #v
 Function calls:
o f([expr1, expr2, …, exprN])
o f{…}
o f"string" or f'string' or f[[string]]
 Retrieves the value in table t:
o t[key]
o t.name

STATEMENTS / CONTROL STRUCTURES


IF-THEN-ELSE

if condition then
-- code
elseif anotherCondition then
-- code
else
-- code
end

FOR LOOPS

For (numeric):
for i=1, 10 do
-- code
end

For (generic):
for key, value in pairs(table) do
-- code
end

WHILE/REPEAT LOOPS

While:
while condition do
-- code
end

Repeat-Until:
repeat
-- code
until condition

LABELS AND GOTO

 Label: ::label::
 Goto label: goto label

FUNCTIONS
BASICS
 Example1:
 function getSum(num1, num2)
 return num1 + num2
end

 Usage: print(string.format("5 + 2 = %d", getSum(5,2)))


 Example2:
 function splitStr(theString)

 stringTable = {}
 local i = 1

 -- Cycle through the String and store anything except for spaces
 -- in the table
 for str in string.gmatch(theString, "[^%s]+") do
 stringTable[i] = str
 i = i + 1
end

MULTIPLE VALUES

 Return multiple values:


 return stringTable, i
end

 Receive multiple values:


splitStrTable, numOfStr = splitStr("The Turtle")

for j = 1, numOfStr do
print(string.format("%d : %s", j, splitStrTable[j]))
end

VARIADIC FUNCTION

 Variadic Function recieve unknown number of parameters


 function getSumMore(...)
 local sum = 0

 for k, v in pairs{...} do
 sum = sum + v
 end
 return sum
end

 Usage:
io.write("Sum : ", getSumMore(1,2,3,4,5,6), "\n")

INVOKING FUNCTIONS

print()
print("Hi")
 You can omit parentheses if the argument is one string or table literal:
 print "Hello World" <--> print("Hello World")
 dofile 'a.lua' <--> dofile ('a.lua')
 print [[a multi-line <--> print([[a multi-line
 message]] message]])
 f{x=10, y=20} <--> f({x=10, y=20})
type{} <--> type({})

CLOSURE

 A Closure is a function that can access local variables of an enclosing


function:
 function outerFunc()
 local i = 0
 return function()
 i = i + 1
 return i
 end
end

TABLES
CREATING TABLES

 Empty table: empty = {}


 With values: list = {1, 2, 3}
 Dictionary: dict = {["a"] = 1, ["b"] = 2, ["c"] = 3}
 Mixed content: mix = {[0] = 0, 1, 2, 3, a = 1, b = 2, c = 3}

ACCESSING VALUES

 Array-style: local value = t[1]


 Dictionary-style: local value = t.key

SETTING VALUES

 t[1] = "a"
 t.key = "value"

ITERATING OVER TABLES

 Pairs (for dictionaries):


 for key, value in pairs(t) do
 -- code
end
 ipairs (for arrays):
 for index, value in ipairs(t) do`
 `-- code`
`end

LOOKUPS

mytable = { x = 2, y = function() .. end }


 The same:
o mytable.x
o mytable['x']
 Syntactic sugar, these are equivalent:
o mytable.y(mytable) = mytable:y()
o mytable.y(mytable, a, b) = 'mytable:y(a, b)
o function X:y(z) .. end = function X.y(self, z) .. end

STANDARD LIBRARIES
STRING LIBRARY

 Concatenation: "Hello " .. "World"


 Length: #str
 Find: string.find(str, substring)
 Replace: string.gsub(str, pattern, replacement)

MATH LIBRARY

 Basic operations: +, -, *, /, //, %


 Power: math.pow(x, y) or x^y
 Square root: math.sqrt(x)
 Trigonometry: math.sin(x), math.cos(x),math.tan(x)

TABLE LIBRARY

 Insert:table.insert(t, value)
 Remove: table.remove(t, position)
 Sort: table.sort(t, compareFunction)

INPUT AND OUTPUT

 Read from standard input: io.read()


 Print to standard output: print("Hello, World!")
 Open a file: local file = io.open(filename, mode)

ADVANCED
METATABLES

Metatables in Lua allow you to change the behavior of tables.

SETTING A METATABLE

local myTable = {}
local myMetatable = {}
setmetatable(myTable, myMetatable)
GETTING A METATABLE

local mt = getmetatable(myTable)

METAMETHODS

Metamethods are special keys in a metatable that correspond to operator


overloads and other behavior modifications.

 __index: Controls behavior when accessing missing keys. Can be a


function or a table.
 __newindex: Controls behavior when setting values to missing keys.
 __call: Allows the table to be called as a function.
 __add, __sub, __mul, __div, __mod, __pow, __unm: Define behavior for
arithmetic operations.
 __eq, __lt, __le: Define behavior for equality and relational
operations.
 __tostring: Defines how a table is converted to a string, useful for
debugging.

MODULES

A Module is like a library full of functions and variables.

 Use require to gain access to the functions in the


module: convertModule = require("convert")
 Execute the function in the module: print(string.format("%.3f cm",
convertModule.ftToCm(12)))

-Module search path: package.path = package.path ..


";/path/to/your/modules/?.lua"

COROUTINES

Coroutines are like threads except that they can't run in parallel (status:
running, susepnded, dead or normal).

 Use create to create one that performs some action


 co = coroutine.create(function()
 for i = 1, 10, 1 do
 print(i)
 print(coroutine.status(co))
 if i == 5 then coroutine.yield() end
end end)
 They start off with the status suspended: print(coroutine.status(co))
 Call for it to run with resume during which the status changes to
running: coroutine.resume(co)
 After execution it has the status of dead: print(coroutine.status(co))

You might also like