lualua-5.4

Lua 5.4 Calling a function declared as a string


I would need to call a function that is declared as a string

i.e local abc = "function x() print('math.sqrt(25)') end"

i've tried load(abc) that gives me no errors but nothing is printed and print(load(abc)) that returns function: 0000000000ebcea0

I've made another tries but nothing seems to suit my case (or probably i'm just bad)


Solution

  • Please read the manual...

    If there are no syntactic errors, load returns the compiled chunk as a function

    If you want that function to be called, call it.

    local abc = "function x() print('math.sqrt(25)') end"
    
    local loadedFunction = load(abc)
    loadedFunction()
    

    or simply

    load(abc)()
    

    Of course you should check wether load actually succeeded.

    If you want something to happen you probably should also call the function that has been defined by the function you loaded.

    load(abc)()
    x()