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

Put in a variable string for a method?

Started by gknova61, 19 November 2012 - 04:44 PM
gknova61 #1
Posted 19 November 2012 - 05:44 PM
Here is the full code:
http://pastebin.com/f2CHf08r

Error is on line 20. You can hopefully see what i'm trying to-do. I can't explain it that well, so but basically

Example:
aDirection = forward
turtle.aDirection()

This just errors attempt to call nil ofc so anyone got any ideas on how to fix this?
remiX #2
Posted 19 November 2012 - 05:49 PM
I've also tried this with term.setTextColours(colours[colour]). Does turtle[aDirection]() not work? This would help me too if someone posts how to get it to work.
Kingdaro #3
Posted 19 November 2012 - 05:53 PM
Short explanation:

aDirection = "forward"
turtle[aDirection]()

Longer explanation:

In the original example you've provided, the script sets variable "aDirection" to "forward", not "turtle.forward". Variable "forward" does not exist, therefore aDirection does not exist either.

On the second line, lua can't directly reference a string from a table using dot notation. It's the same as doing

turtle."forward"()
which obviously doesn't work. To get around this, you would put brackets around your string, and remove the dot.

turtle["forward"]()
gknova61 #4
Posted 19 November 2012 - 05:54 PM
Seems it does, thanks! May I ask the reasoning behind that working? I'm just trying to learn more about lua :(/>/> Thanks KingDoro for the explanation!
remiX #5
Posted 19 November 2012 - 06:07 PM
Short explanation:

aDirection = "forward"
turtle[aDirection]()

So I was right :(/>/> Thanks from me too for the explanation.