lua.lua 981 B

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