Being able to iterate through data for the purpose of reading it or manipulating it is very important when it comes to scripting as it is a real time saver. There are multiple different ways to create iteration loops & loops in general with Lua script.
Quick note: iteration loops will automatically pause all lines after them until the for loop has finished, which is why in the first example below I can get away with adding the print message after the function & as you can see, it printed the entire message.
|
Iteration
Below I am going to show you how to use the 3 main types of for iteration loops.
for i equals 1
iterate through an index table |
|
local t = {"Hi,", "my", "name", "is", "Barry."}
local str = ""
for i = 1, #t do -- for variable equals 1 to table total entries do
str = str .. t[i] -- insert string from table based on current index value into the str variable
if i < #t then str = str .. " " end -- if i is less than table total then insert white space after each word
end
print(str) -- print the content of the str variable to the log print(str)
|
|
Variable as Function
print hello world! |
|
hello = function()
print("hello world!")
end
hello()
|
|
Function with Input Arguments
print 6 |
|
function plus(a, b)
return a + b
end
print( plus(2, 4) )
|
|
Input Arguments and Fallback
print 0.5, 5 |
|
function divideAndConquer(a, b, c)
c = c or 1 -- if c equals nil then c equals 1
return (a / b) * c
end
print( divideAndConquer(2, 4) ) -- 2 ÷ 4 x 1 = 0.5
print( divideAndConquer(2, 4, 10) ) -- 2 ÷ 4 x 10 = 5
|
|