function mymax(a, b)
return ((a>b) and a) or b
end
mymax(1) --> mymax (1, nil)
mymax(1,2,3) --> mymax (1,2), 3 is discarded
e.g.
function inc (n)
n = n or 1
count = count + n
end
s, e = string.find("hello lua users", "lua")
return a,b
a special function unpack()
, which can be used as generic call mechanism.
function unpack (t, i)
i = i or 1
if t[i] then
return t[i], unpack (t, i+1)
end
end
function add (...)
local s = 0
for i, v in ipairs {...} do
s = s + v
end
return s
end
print (add(1,2,3,4,5,6))
-- original
function foo (a, b, c)
-- alternative, perl-like
function foo (...)
local a, b, c = ...
-- STUFF
end
multi-value identity
function id (...) return ... end
debug/trace use example
function foo_debug (...)
print ("I: Calling foo(", ..., ")")
return foo (...)
end
function fwrite (fmt, ...)
return io.write (string.format(fmt, ...))
end
sometimes the argument list contains some nil, at that time select()
should be used.
for i = 1, select ('#', ...) do --> select('#',...) returns the total size of the argument list, including nil.
local arg = select (i, ...) --> fetch the i-th argument
STUFF
end
rename (old="temp.lua", new="temp1.lua")
is not supported directly in Lua.
function rename (arg)
return os.rename (arg.old, arg.new)
end
rename ({old = "temp.lua", new = "temp1.lua"}) --> "(" ")" can be omitted.