Jump to content




<Solved> Accessing Turtle Functions In _G


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

#1 iownall555

  • Members
  • 54 posts

Posted 07 August 2013 - 03: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.

#2 OmegaVest

  • Members
  • 436 posts

Posted 07 August 2013 - 03: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>.

#3 Kingdaro

    The Doctor

  • Members
  • 1,636 posts
  • Location'MURICA

Posted 07 August 2013 - 03: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.

#4 iownall555

  • Members
  • 54 posts

Posted 07 August 2013 - 04: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.





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users