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

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

Started by SGunner2014, 30 December 2015 - 11:02 AM
SGunner2014 #1
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 on 30 December 2015 - 08:46 PM
LBPHacker #2
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 on 30 December 2015 - 12:19 PM
KingofGamesYami #3
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.
LBPHacker #4
Posted 30 December 2015 - 01:45 PM
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.
Creator #5
Posted 30 December 2015 - 09:34 PM
Write a custom unserializer that automatically sets the environement to something.