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

Storing Function In A Table

Started by bigbaddevil6, 07 September 2013 - 11:51 PM
bigbaddevil6 #1
Posted 08 September 2013 - 01:51 AM
So exactly what im trying to do is make it where a function can be stored into a table so pretty much something like this. Extremely crude example below.


local commands = {talk, sleep, sing, dance} -- table to store the functions
function talk()
	print("I talked")
end
function sleep()
	print("I slept")
end
function sing()
	print("I sung")
end
function dance()
	print("I danced")
end
talk = talk()
sleep = sleep()
sing = sing()
dance = dance()

message = read() -- message that would be checked against the table

So i want it so when someone type in "speak" it would use an if statement to check the table find the speak function stored and then executes the function. The reason it need to be a table is because its going to be check for alot more than just for 4 different commands so thought if the if statement could loop through the table wouldn't 100's of elseif statements.
bigbaddevil6 #2
Posted 08 September 2013 - 02:10 AM
I found a tut on it in the tutorial section http://www.computercraft.info/forums2/index.php?/topic/10508-how-to-make-and-use-a-look-up-table/
Engineer #3
Posted 08 September 2013 - 03:05 AM
You are storing variables which are not defined yet, try something like this:

local commands = {}
function commands.sleep() 
  print( "I slept" )
end 
-- etc 

--execute the function
local exe = read()
if commands[ exe ] then
  commands[ exe ]()
end
bigbaddevil6 #4
Posted 08 September 2013 - 03:22 AM
yea I managed to rewrite it to pretty much that exact way as you explained it and so far is working perfectly, which is always nice