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

<Solved> Accessing Turtle Functions In _G

Started by iownall555, 07 August 2013 - 02:28 PM
iownall555 #1
Posted 07 August 2013 - 04:28 PM
Now I'm a bit confused here but what I'm attempting to do is access the turtle table inside the _G table (the globals). I'm creating a program to remotely control my turtles and I want to be able to put a command into a variable and call that variable as a function. For example, if the turtle was send "forward" it would create a string that has the value "turtle.forward()" and then call it from the global table so I don't need to use lots of if statements to make the turtle do my bidding.

Code: http://pastebin.com/Ark26Nu5

I tried manually printing _G and it comes up with a list of tables (as you would expect) however I'm not sure how to access the "turtle" table from within _G.

Edit: Problem is around line 36

Any help would be appreciated.
Thanks.
OmegaVest #2
Posted 07 August 2013 - 04:39 PM
…You can do that much more simply just using the turtle API.


runCmd(cmd)  -- Assuming that cmd is a valid function name, not an alias.
  print("rc: ", cmd)
  turtle[cmd]()
end

Should work, really. If you are set on using _G, it should still work this way, I think. I don't really deal with the Global Table directly, though, because, frankly, it's usually called for you anyway. Just typing out a variable name (so far as I know, which isn't all that far) should assume _G.<whatever you are calling>.
Kingdaro #3
Posted 07 August 2013 - 04:41 PM
The logic there is a little broken.

The turtle table in _G is indexed under _G as "turtle", and every function under _G["turtle"] is a sub index, e.g. _G["turtle"]["forward"], except a much better way to say that would just be turtle.forward.

For your problem, accessing _G is completely unnecessary. All you'd need to do is this:

local func = turtle[cmd]
func()

In order to get the turtle function that corresponds with the command given to you over rednet.
iownall555 #4
Posted 07 August 2013 - 05:41 PM
That make a lot more sense now since turtle functions are stored in a table.

I don't know how I completely missed that. Haha.

Thanks to both of you for pointing that out.