[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Use byte-code directly?
- From: Fabio Mascarenhas <fabiomasc@...>
- Date: Fri, 17 Sep 2004 18:04:40 -0300
George Warner wrote:
I was able to do the "luac -l" trick to dump the tokens like this:
function <zebnig:2368> (11 instructions, 44 bytes at 0x11fc50)
1 param, 9 stacks, 0 upvalues, 5 locals, 2 constants, 0 functions
1 [2369] MOVE 1 0 0
Position 0 is your first parameter (a table, in this case). This line is
just setup for TFORPREP, as it overwrites the stack position of its
first argument.
2 [2369] LOADNIL 2 4 0
Again, setup for TFORPREP, as it will use next for generator function,
and it takes a table and a key as arguments. Passing nil makes it return
the first key. If you had used the pairs function the code would be
slightly clearer. :-)
3 [2369] TFORPREP 1 5 ; to 9
Transforms table for into generator for, using function next as the
generator. After executing this opcode, stack 1 is next, stack 2 is the
table to be traversed, stack 3 is nil. It immediately jumps to the
TFORLOOP instructor.
4 [2370] GETGLOBAL 5 0 ; dprint
Stores dprint in stack 5 for calling later on.
5 [2370] MOVE 6 3 0
First argument for dprint (the first value returned by next, a table key).
6 [2370] LOADK 7 1 ; ":"
Second argument for dprint (the constant ":")
7 [2370] MOVE 8 4 0
Third argument for dprint (the seconde value returned by next, a table
value)
8 [2370] CALL 5 4 1
Calls dprint, telling it that it will receive 3 arguments (4-1) and
discards return values (1-1). Both are -1 because if they are 0 you
repsectively call the function with everything in the stack after it (up
to top), and keeps all return values. This is for calls like:
foo(bar())
bar will be called with CALL x 1 0 and foo with CALL y 0 1, respectively.
9 [2369] TFORLOOP 1 0 1
Executes next with the values on stack 2 and stack 3. Next will return a
key in stack 3 and a value in stack 4. Skips the next instruction if the
loop ends (next returns nil).
10 [2370] JMP 0 -7 ; to 4
Goes back to the start of the loop.
11 [2372] RETURN 0 1 0
Returns, telling that there are no return values (1-1). The first
parameter is where the return values start in the stack, if the function
will return any. If the second parameter is 0 then it returns everything
in the stack from the first parameter to the top, for cases like
return foo().
But what would be the source for this function?
Given all above, the source is:
function zebnig(table)
for k,v in table do
dprint(k, ":", v)
end
end
I strongly recommend you to take a good read of lopcodes.h and the main
switch in lvm.c if you have any doubts. :-) If in doubt, type the code
and run luac to see if it checks (the one above checks line for line).
--
Fabio Mascarenhas