lua-users home
lua-l archive

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


On 01/07/2011 9.08, steve donovan wrote:
On Fri, Jul 1, 2011 at 8:42 AM, steve donovan<steve.j.donovan@gmail.com>  wrote:
[1] http://lua-users.org/wiki/ExpressionsAsStatements

I must share one gem from that page, from the ever-prolific Rici Lake:

repeat until nsfm:fileExistsAtPath(testfile) or Shriek "File doesn't exist"

The 'repeat until' is a mouthful, but giving it a new name is a good
job for a preprocessor.


I got curious and wrote:

-------------------
local function condition_ok()
end
local function E()
end

repeat until condition_ok() or error "AAARGHH!"

local _ = condition_ok() or error "AAARGHH!"

E( condition_ok() or error "AAARGHH!" )

print "hooray!"
-------------------

Lua 5.1.4 gives as bytecode (comments added):



main <lua_scratchpad2.lua:0,0> (31 instructions, 124 bytes at 003D3D40)
0+ params, 6 slots, 0 upvalues, 3 locals, 4 constants, 2 functions
	1	[3]	CLOSURE  	0 0	; 003D3E68
	2	[5]	CLOSURE  	1 1	; 003D3F90

-- "repeat until" version

	3	[7]	MOVE     	2 0
	4	[7]	CALL     	2 1 2
	5	[7]	TEST     	2 0 1
	6	[7]	JMP      	5	; to 12
	7	[7]	GETGLOBAL	2 -1	; error
	8	[7]	LOADK    	3 -2	; "AAARGHH!"
	9	[7]	CALL     	2 2 2
	10	[7]	TEST     	2 0 0
	11	[7]	JMP      	-9	; to 3

-- "local _" version

	12	[9]	MOVE     	2 0
	13	[9]	CALL     	2 1 2
	14	[9]	TEST     	2 0 1
	15	[9]	JMP      	3	; to 19
	16	[9]	GETGLOBAL	2 -1	; error
	17	[9]	LOADK    	3 -2	; "AAARGHH!"
	18	[9]	CALL     	2 2 2

-- "E(...)" version

	19	[11]	MOVE     	3 1
	20	[11]	MOVE     	4 0
	21	[11]	CALL     	4 1 2
	22	[11]	TEST     	4 0 1
	23	[11]	JMP      	3	; to 27
	24	[11]	GETGLOBAL	4 -1	; error
	25	[11]	LOADK    	5 -2	; "AAARGHH!"
	26	[11]	CALL     	4 2 2
	27	[11]	CALL     	3 2 1


	28	[13]	GETGLOBAL	3 -3	; print
	29	[13]	LOADK    	4 -4	; "hooray!"
	30	[13]	CALL     	3 2 1
	31	[13]	RETURN   	0 1

function <lua_scratchpad2.lua:2,3> (1 instruction, 4 bytes at 003D3E68)
0 params, 2 slots, 0 upvalues, 0 locals, 0 constants, 0 functions
	1	[3]	RETURN   	0 1

function <lua_scratchpad2.lua:4,5> (1 instruction, 4 bytes at 003D3F90)
0 params, 2 slots, 0 upvalues, 0 locals, 0 constants, 0 functions
	1	[5]	RETURN   	0 1



So it seems that the most efficient is "local _ = ...": less bytecode and no extra function calls.



Actually, there is one special kind of expression which is allowed as
a statement, and that is a function call. Allowing _any_ expression to
be a statement would probably result in grammatical ambiguities.

steve d.