Log In  

Hey, everybody. In the Toy Train tutorial in PicoZine 1, the first function created looks like this:

function move_segment(s,dir)
spd=dir*2
if(s[2]==8) --TOP SIDE
then
if(s[ 1]==112) --top RIGHT
then
s[2]+=spd
else
s[ 1]+=spd
end
...

And on like that. There must be something I don't get about function arguments/parameters, because the whole function hinges on the relationships between spd, dir, and s - but spd and dir are never defined...! Just what is going on here? It really flies in the face of everything I've learned about code to this point. Where the hell is it getting any type of value? Dir isn't even used again in this entire cart. I'm so confused.

I've looked at several function tutorials, but haven't seen this explained... At least not in a way I'm able to understand. Clearly I'm not the brightest or most informed, but jeez louise this confounded me. Because I don't know what exactly this behavior is called, I don't know what I can search for to learn more about this behavior.

If anyone wants to look at the cart/entire body of code, here's the link.

Thanks so much.

P#46468 2017-11-19 12:25 ( Edited 2017-11-19 23:57)

So you're defining the variable 'spd' in the first line of the function, giving it the value of two times the value of 'dir'.

'dir' is a parameter to the 'move_segment' function. It gets a value assigned from wherever you call 'move_segment' (In this case in the 'move_train' function, which is defined later in the tutorial. In that case it gets given the value of 'switch_state' - itself created in _init and updated in the function 'adv_switch').

A little detail:

In Lua, you can just type a variable name and give it a value anywhere in your code.

If you do something like:

foo=32

...then any code that executes afterwards can refer to the variable foo (this would be a 'global' variable'). This is kind of what is happening with 'spd'. It would probably be more correct to write:

local spd=dir*2

...but either way is fine, provided you don't need another spd variable elsewhere.

Let me know if that helps or if you need more detail :)

P#46470 2017-11-19 12:48 ( Edited 2017-11-19 17:48)

@Powersaurus Oh, I see - the complexity was just a little over my head, but nothing out of the ordinary was going on. Thank you for clearing that up, I do understand much better now. I feel bad wasting a whole new thread. Hopefully someday soon I'll contribute something that'll make up for all the hand-holding I have to ask for now.Thanks for being so helpful!

P#46475 2017-11-19 14:06 ( Edited 2017-11-19 19:06)

No problem! The way Lua variables are is not the most intuitive to start with. Can throw up some surprises.

P#46486 2017-11-19 18:57 ( Edited 2017-11-19 23:57)

[Please log in to post a comment]

Follow Lexaloffle:          
Generated 2024-03-28 15:41:58 | 0.010s | Q:12