lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


In message <20030618135518.GA29228@malva.ua>, Max Ischenko writes:
> Hi,
> 
> I have this code snippet:
> 
> 
> function compile(spec)
> 	local funcBody = string.format('return function() return %s end', spec)
> 	return loadstring(funcBody)
> end
> 
> f = compile('2==3')
> print(f())
> 
> This prints 0 on Lua 4.0 and function: 0x804eb60 on Lua 5.0
> To print false (a.k.a 0) in Lua 5.0 I had to wrote
> print(f()())
> 
> Why I this? Did I write compile function wrong?

Presumably you were using dostring in Lua 4.0 and are now using
loadstring in Lua 5.0?  Although the manual deprecates dostring in
favour of loadstring they do not have identical behaviour.

dostring will compile _and_ execute the string.

loadstring will compile it and return a function that when called has
the same effect as executing the string.

In Lua 4.0 this 'return function() return ... end' was a way to achieve
the delayed execution that loadstring already does in Lua 5.

Summary:

in Lua 5.0 use

function compile(spec)
  return loadstring(string.format('return %s', spec))
end

Hope that helps.

Cheers,
 drj