lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


于 2013-10-31 22:13, Dario Dominin 写道:
Guys,
finally I found the time to practice a bit with LUA ...

I wrote a simple code
...

My idea is to have 3 squares ... and after click the first square ... move exchange the position of square1 and square2.

I have 2 question:

1. I did the transition of square1 in 3 steps (up (line34) then right (line38) and finally down (line40)) .. but instead of the separate movements .. I have only one .. on the right :( why?



I've no idea what GUI system you are using, but I guess the reason why you didn't see
the transition animation is that the 3 steps were done with no delay so the intermediate
state is displayed in too short a period to be seen.

To see the animation effect, you might insert pauses in between.
However, if you simply sleep, the GUI event loop can be blocked so the GUI would be
not responding during the animation.
A better way is to schedule each transition step at some delayed time.
Refer to the documentation of your GUI library to find the appropriate solution.

Or, maybe your GUI library already provided some mechanisim to do simple animation.

2. Due to I want randomly move one of the squares .. I tried creating a table like

T1 = { S1="square1", S2="square2", S3="square3"}


I was thinking to use T1.[S1] in the transition call .. but nothing move even if T1.S1 contains correctly the "square1" value ... but maybe is only a text ..how to use it as "variable" name?




First of all, you must really understand the variable and scope concepts in Lua.

To be simple, global variables in Lua is implemented as table entries
of the ENVIRONMENT table of the function(closure).
If you are using the oficial (not customized, I mean) Lua 5.2, just use the 'name' as a key
to index into the _ENV table, like _ENV['square1'], or _ENV[T1.S1].
For Lua 5.1, probably _G['square1'] would work.

See the documentation of '_ENV', '_G', and 'getfenv' for detailed information.


But I would suggest another solution rather than using 'variable names'.
Just utilize the power of Lua's lexical scope, and store the object directly in the table.
Something looks like this:

-------------------------------------------------
....
local square1 = {
-- initialize the object
....
}
....
-- store the object for later use
T1 = { S1 = sqaure1,
....
}
....
-- use the table to refer the object
T1.S1:moveto(....)
-------------------------------------------------