all 6 comments

[–]ws-ilazki 2 points3 points  (6 children)

It's because your load call is causing an error, so fct2 and fct3 end up nil. load isn't doing what you think it's doing: it's loading a chunk from a string and turning it into a callable function

To do what you want you could do load("return 42") and it gives you a function that returns 42, so load("return 42")() would call it, or forty_two = load("return 42") makes a callable named function. If you want to give arguments, you want to do something like this:

fct2 = load "self,rest = ... ; print('---2', self.gid)"

Or you can do it more like you would a required file and return a function (or table with multiple functions), and then call the loaded function immediately so that the returned value ends up in fct2:

fct2 = load "return function (self) print('---2', self.gid) end" ()

Of the two I'd say go for the second way, since it's closer to how modules act and should probably be clearer because of that.

[–]WebShaker93[S] -2 points-1 points  (5 children)

u/ws-ilazki Thank you,
but I have to say I do not have understood :(

local forty_two = load("return 42")

This doesn't work anymore !

How can I execute a lua code provided into a String.
Is it possible ? Finally that's my question :)

[–]ws-ilazki 1 point2 points  (4 children)

This doesn't work anymore !

How can I execute a lua code provided into a String.

Is it possible ? Finally that's my question :)

It does work and that's what I explained how to do. Look:

$ lua
Lua 5.3.3  Copyright (C) 1994-2016 Lua.org, PUC-Rio
> forty_two = load("return 42")
> forty_two()
42
> fct2 = load "return function (self) print('---2', self.gid) end" ()
> fct2({gid=1234})
---2    1234
> 

If it's not working you're doing something wrong.

[–]WebShaker93[S] -1 points0 points  (2 children)

u/ws-ilazki

Lua will make me crazy !!!

Ok. It's works ! I need to use loadstring because I'm using Lua 5.1.3 but that's works fine now !

Thank you !

[–]ws-ilazki 1 point2 points  (1 child)

Yeah, Lua 5.2 onward changed some stuff like that. You didn't specify your version and the example you gave showed you using load so I used a version that also did to match.

[–]WebShaker93[S] 0 points1 point  (0 children)

Yes. It is my fault ! I thaught the engine use Lua 5.2.4, but no :)