Debian Codegraph @

demo/kitchen-sink/docs/lua.lua

raw
1 --[[--
2 num_args takes in 5.1 byte code and extracts the number of arguments
3 from its function header.
4 --]]--
5
6 function int(t)
7 return t:byte(1)+t:byte(2)*0x100+t:byte(3)*0x10000+t:byte(4)*0x1000000
8 end
9
10 function num_args(func)
11 local dump = string.dump(func)
12 local offset, cursor = int(dump:sub(13)), offset + 26
13 --Get the params and var flag (whether there's a ... in the param)
14 return dump:sub(cursor):byte(), dump:sub(cursor+1):byte()
15 end
16
17 -- Usage:
18 num_args(function(a,b,c,d, ...) end) -- return 4, 7
19
20 -- Python styled string format operator
21 local gm = debug.getmetatable("")
22
23 gm.__mod=function(self, other)
24 if type(other) ~= "table" then other = {other} end
25 for i,v in ipairs(other) do other[i] = tostring(v) end
26 return self:format(unpack(other))
27 end
28
29 print([===[
30 blah blah %s, (%d %d)
31 ]===]%{"blah", num_args(int)})
32
33 --[=[--
34 table.maxn is deprecated, use # instead.
35 --]=]--
36 print(table.maxn{1,2,[4]=4,[8]=8}) -- outputs 8 instead of 2
37
38 print(5 --[[ blah ]])