Advertisement
imring

[LUA] get table

Mar 2nd, 2019
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.27 KB | None | 0 0
  1. local val_to_str, key_to_str, tabletostring
  2. local char, byte, gsub, match, sub, find =
  3.     string.char, string.byte, string.gsub, string.match, string.sub, string.find
  4. local insert, concat = table.insert, table.concat
  5.  
  6. function val_to_str ( v )
  7.     if "string" == type( v ) then
  8.         v = gsub( v, "\n", "\\n" )
  9.         if match( gsub(v,"[^'\"]",""), '^"+$' ) then
  10.             return "'" .. v .. "'"
  11.         end
  12.         return '"' .. gsub(v,'"', '\\"' ) .. '"'
  13.     else
  14.         return "table" == type( v ) and tabletostring( v ) or
  15.             tostring( v )
  16.     end
  17. end
  18.  
  19. function key_to_str ( k )
  20.     if "string" == type( k ) and match( k, "^[_%a][_%a%d]*$" ) then
  21.         return k
  22.     else
  23.         return "[" .. val_to_str( k ) .. "]"
  24.     end
  25. end
  26.  
  27. function tabletostring( tbl )
  28.     local result, done = {}, {}
  29.     for k, v in ipairs( tbl ) do
  30.         insert( result, val_to_str( v ) )
  31.         done[ k ] = true
  32.     end
  33.     for k, v in pairs( tbl ) do
  34.         if not done[ k ] then
  35.             insert( result,
  36.             key_to_str( k ) .. "=" .. val_to_str( v ) )
  37.         end
  38.     end
  39.     return "{" .. concat( result, "," ) .. "}"
  40. end
  41.  
  42. if _ARGS == '' then return 'error.' end
  43. local tab = _ENV[_ARGS]
  44. local bool = false
  45. if _ARGS == '_ENV' then tab = _ENV; bool = true end
  46. if type(tab) ~= 'table' then return 'error.' end
  47. return (bool and '_ENV' or _ARGS) .. ' = ' .. tabletostring(tab)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement