Jump to content




Calling Functions from a table


  • You cannot reply to this topic
5 replies to this topic

#1 civilwargeeky

  • Members
  • 393 posts

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.

#2 Orwell

    Self-Destructive

  • Members
  • 1,091 posts

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?

#3 civilwargeeky

  • Members
  • 393 posts

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.

#4 ChunLing

  • Members
  • 2,027 posts

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,
}


#5 civilwargeeky

  • Members
  • 393 posts

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.

#6 ChunLing

  • Members
  • 2,027 posts

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.





3 user(s) are reading this topic

0 members, 3 guests, 0 anonymous users