Log In  

-- converts anything to string, even nested tables
function tostring(any)
    if type(any)=="function" then 
        return "function" 
    if any==nil then 
        return "nil" 
    if type(any)=="string" then
        return any
    if type(any)=="boolean" then
        if any then return "true" end
        return "false"
    if type(any)=="table" then
        local str = "{ "
        for k,v in pairs(any) do
            str=str..tostring(k).."->"..tostring(v).." "
        return str.."}"
    if type(any)=="number" then
        return ""..any
    return "unkown" -- should never show

Example usage:

> print(""..tostring({true,x=7,{"nest"}}))
{ 1->true 2->{ 1->nest } x->7 }
P#43636 2017-08-26 07:12 ( Edited 2017-12-07 14:13)

nice! would be a great addition to the pico8 api. tables are a pain to debug.

P#43637 2017-08-26 07:39 ( Edited 2017-08-26 11:39)
:: Felice

I imagine a lot of us have made something similar. I have a ton of pretty-printing stuff. Lua's string-ifying isn't the greatest in the first place, and even then, Pico-8 doesn't provide its full facilities. Pretty inconvenient when you have to debug with print(). It'd be nice if there was better native support.

P#43639 2017-08-26 11:33 ( Edited 2017-08-26 15:33)
:: sulai

@Felice,ultrabrite I totally agree, debugging in pico-8 is hard and not being able to print whatever, makes it even harder. Would be cool if pico-8 did this natively.

P#43653 2017-08-26 15:50 ( Edited 2017-08-26 19:50)

It would be much simpler if the tostr() function just converted as table to a string of the table's values rather than just "[table]". I always have to make for loops in order to see what in a table is causing me issues.

P#47178 2017-12-07 09:13 ( Edited 2017-12-07 14:13)
:: pjaros

Thank you for your code. While debugging I was looking for a function that would do the exact same thing.

I took your code and improved upon it.

-- converts anything to string, even nested tables
function tostring(any)
  if (type(any)~="table") return tostr(any)
  local str = "{"
  for k,v in pairs(any) do
    if (str~="{") str=str..","
  return str.."}"

This will print like this

> t = {5, {c="b"}, 'a', true}
> print(tostring(t))
P#67393 2019-09-08 08:33

[Please log in to post a comment]

Follow Lexaloffle:        
Generated 2020-10-27 18:42 | 0.017s | 2097k | Q:23