lua-users home
lua-l archive

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


 On Behalf Of Nick Davies> Sent: March 3, 2003 6:41 PM
> 
> In the following code:
> 
> ===
> function create()
>     local e
>     e.x = 0
>     e.update = function(self)    -- mark
>         self.x = self.x + 1
>     end
>     return e
> end
> 
> e1 = create()
> e2 = create()
> e3 = create()
> ===
> 
> How many copies are created of the 'update' function at the 
> marked line?
> One, shared among e1, e2, and e3, or three, one for each of 
> e1, e2, and e3?
> 
> I am planning on doing this sort of thing quite a bit in my 
> current Lua
> project and I'm concerned a bit about memory efficiency and such.

Lua script:

function create()
    local e = {}
    e.x = 0
    e.update = function(self)    -- mark
        self.x = self.x + 1
    end
    return e
end

e1 = create()
e2 = create()
e3 = create()

e1:update()


luac generates the follow output:

main <0:@/tmp/wl44qZp8> (15 instructions/60 bytes at 0x8052af0)
0 params, 2 stacks, 0 locals, 5 strings, 0 numbers, 1 function, 9 lines
     1	[8]	CLOSURE    	0 0	; 0x8052be8
     2	[8]	SETGLOBAL  	0	; create
     3	[10]	GETGLOBAL  	0	; create
     4	[10]	CALL       	0 1
     5	[10]	SETGLOBAL  	1	; e1
     6	[11]	GETGLOBAL  	0	; create
     7	[11]	CALL       	0 1
     8	[11]	SETGLOBAL  	2	; e2
     9	[12]	GETGLOBAL  	0	; create
    10	[12]	CALL       	0 1
    11	[12]	SETGLOBAL  	3	; e3
    12	[14]	GETGLOBAL  	1	; e1
    13	[14]	PUSHSELF   	4	; update
    14	[14]	CALL       	0 0
    15	[14]	END

function <1:@/tmp/wl44qZp8> (12 instructions/48 bytes at 0x8052be8)
0 params, 4 stacks, 1 local, 2 strings, 0 numbers, 1 function, 9 lines
     1	[2]	CREATETABLE	0
     2	[3]	GETLOCAL   	0	; e
     3	[3]	PUSHSTRING 	0	; "x"
     4	[3]	PUSHINT    	0
     5	[3]	SETTABLE   	3 3
     6	[4]	GETLOCAL   	0	; e
     7	[4]	PUSHSTRING 	1	; "update"
     8	[6]	CLOSURE    	0 0	; 0x8052d48
     9	[6]	SETTABLE   	3 3
    10	[7]	GETLOCAL   	0	; e
    11	[7]	RETURN     	1
    12	[8]	END

function <4:@/tmp/wl44qZp8> (7 instructions/28 bytes at 0x8052d48)
1 param, 5 stacks, 1 local, 1 string, 0 numbers, 0 functions, 4 lines
     1	[5]	GETLOCAL   	0	; self
     2	[5]	PUSHSTRING 	0	; "x"
     3	[5]	GETLOCAL   	0	; self
     4	[5]	GETDOTTED  	0	; x
     5	[5]	ADDI       	1
     6	[5]	SETTABLE   	3 3
     7	[6]	END


*** a closure is created in every function call to create() but this
only creates one function.

BTW: local e = {}

from: http://doris.sourceforge.net/lua/weblua.php

You can make the output more readable using:
http://lua-users.org/wiki/VmMerge

N