This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
Cyclonit's profile picture

Custom "toString" function

Started by Cyclonit, 19 July 2012 - 05:42 PM
Cyclonit #1
Posted 19 July 2012 - 07:42 PM
Hi,

I just wrote a pair of functions which should turn any given variable into a string (in theory). However if I print both the type of the result and the result itself I get this:

string, table: 5dff0f89

These are the functions:

-- Escapes characters in variables to prevent them from breaking the database.
function escape(str)

    local orig = {"/", "=", "{", "}", ",", "n"}
    local escaped = {"/1", "/2", "/3", "/4", "/5", "/6"}

    for i, char in ipairs(orig) do
  	  str = string.gsub(str, char, escaped[i])
    end

    return str

end


-- Converts the given value into a string.
function toString(value)

   -- tables
   if (type(value) == table) then

      for i=1, #value, 1 do
         value[i] = toString(value)
      end

      return ( "{" .. table.concat(toString(value), ",") .. "}" )

   -- other
   else
       return escape(tostring(value))
   end

end

I dunno what I did wrong…

Cyclonit
MysticT #2
Posted 19 July 2012 - 08:23 PM
type returns a string, so this:

if (type(value) == table) then
should be:

if (type(value) == "table") then
Cyclonit #3
Posted 19 July 2012 - 11:05 PM
Thank you very much =)