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

Calling Functions from a table

Started by civilwargeeky, 22 December 2012 - 04:12 PM
civilwargeeky #1
Posted 22 December 2012 - 05:12 PM
EDIT: Solved, User Error. I actually did know what I was doing.


So I'm making a program that will move a turtle based on tArgs[1]. It sets it to 'command' and then defines all my functions (six directions).

so then I define:

commands = {forward = forward, right = right, left = left, backward = backward,
down = down, up = up }
so that every function has a key that I can call. Now, when I do

commands[command]()

it works but prints the key (I guess) to the screen. Now I figured out that

commands.command()

dosen't work (although it does print the key). Please help me figure this out.
Orwell #2
Posted 22 December 2012 - 05:25 PM
Except for that it prints the keys, it looks all fine to me. Maybe you should post the entire code you last tried so that we can see the whole picture?
civilwargeeky #3
Posted 22 December 2012 - 05:30 PM
Oh my. I guess this actually does work fine. I realized in the start I put:

tArgs = {...}
command = tArgs[1]
print(command)
to debug it earlier. Terribly sorry for wasting your time Orwell.
ChunLing #4
Posted 22 December 2012 - 05:32 PM
It looks fine but not very useful. Having values identical to the keys doesn't do much, since you could just use whatever you're using to access them as they are.

If you want to call them, then they should be functions, like so:
commands = {
    forward = function()
    --do some stuff
    end,
    right = function()
    --do some stuff
    end,
    left = function()
    --do some stuff
    end,
    backward = function()
    --do some stuff
    end,
    down = function()
    --do some stuff
    end,
    up = function()
    --do some stuff
    end,
}
civilwargeeky #5
Posted 22 December 2012 - 07:08 PM
Thanks also ChunLing but I cant call the function from a variable if it's not in a table (or can I?), and to avoid using number I used keys. That probably would have been smart to define the functions in the table though. Thanks.
ChunLing #6
Posted 22 December 2012 - 08:04 PM
You can easily call these using variables, as long as the variable holds a string that matches the key.
if commands[var] then commands[var]() end
I do it all the time.