Jump to content




Table with functions saved as file. Not working when unserialised?


  • You cannot reply to this topic
4 replies to this topic

#1 SGunner2014

  • Members
  • 113 posts
  • LocationMaidstone, UK

Posted 30 December 2015 - 12:02 PM

Hi all,

I'm trying to create a utility for my OS, and I need a way to store a table, with some functions in said table. However, when I use textutils.unserialise on the file, I can no longer use the functions in that table. Here is an example of an app file for my utility:

So, for example, when the user hits the button with the actin example, then the function example should be run. However, the function example is never run as apparently it it not a function after using textutils.unserialise?

If anyone could help me, I would be very grateful.

Thanks,
- Sam

Edited by SGunner2014, 30 December 2015 - 09:46 PM.


#2 LBPHacker

  • Members
  • 766 posts
  • LocationBudapest, Hungary

Posted 30 December 2015 - 01:16 PM

That's probably because textutils.unserialize unserializes the string by loading it (plus a "return " .. bit) as a chunk and running it as a function. The environment table of said function is set to {} (empty table) (rom/apis/textutils:300). Your functions.example function attempts to index print, but there's no print in its empty environment table, so the result of the value lookup is nil. When it tries to call that, it dies silently.

Solution: Do the dirty work yourself.
-- modified version of textutils.unserialize
local function unserialize( s )
    local func = load( "return "..s, "unserialize", "t", _G ) -- use _G here instead of {}
    if func then
        local ok, result = pcall( func )
        if ok then
            return result
        end
    end
    return nil
end

Edited by LBPHacker, 30 December 2015 - 01:19 PM.


#3 KingofGamesYami

  • Members
  • 3,002 posts
  • LocationUnited States of America

Posted 30 December 2015 - 01:33 PM

As an alternative to LBP's example, you could use setfenv. This'll be useful if something you need to use isn't in _G.

#4 LBPHacker

  • Members
  • 766 posts
  • LocationBudapest, Hungary

Posted 30 December 2015 - 01:45 PM

 KingofGamesYami, on 30 December 2015 - 01:33 PM, said:

setfenv
Oh how I miss setfenv. I mentioned load-time environment setting because setfenv is getting obsolete. One could just supply unserialise with an environment table anyway.

#5 Creator

    Mad Dash Victor

  • Members
  • 2,168 posts
  • LocationYou will never find me, muhahahahahaha

Posted 30 December 2015 - 09:34 PM

Write a custom unserializer that automatically sets the environement to something.





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users