This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
doublequestionmark's profile picture

Execute code in a table

Started by doublequestionmark, 18 June 2015 - 11:55 PM
doublequestionmark #1
Posted 19 June 2015 - 01:55 AM
ok, so i have a table like this in my cc program:


Table = {
	    "print('Hello')",
	    "print('Im in a table')",
	    "for i=1,10 do print('Tables are cool') end"
}

i need a way to execute the code in the table, for example:


example(Table[3]) -- could print `Tables Are Cool` ten times

how would i go about doing this?
Quintuple Agent #2
Posted 19 June 2015 - 02:15 AM
to execute a string all you have to do is

local exeTab = loadstring("print('hello')")
exeTab()
I would suggest reading the lua tutorial page for this
Also an FYI, if the code inside loadstring is invalid and would throw an error the exeTab return nil plus an error message
From the tutorial page
print(loadstring("i i"))
–> nil [string "i i"]:1: `=' expected near `i'
Dog #3
Posted 19 June 2015 - 02:29 AM
If the table entries don't need to be strings, you could do something like this…

local myTable = { function() print('hello') end, function() print("I'm in a table") end, function() for i = 1, 10 do print('Tables are cool') end end }

then you could call myTable[3]() and it would print 'Tables are cool' ten times.
MKlegoman357 #4
Posted 19 June 2015 - 05:56 AM
Dog's right. Even though compiling Lua code on the fly us 'cool n stuff' but it's not that efficient. If possible please stay with actual functions instead of strings. You could also tell us why you need it so we could suggest to you the best solution.