lua-users home
lua-l archive

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


On Sun, Jul 20, 2008 at 9:54 PM, Cooper Clauson <ceclauson@hotmail.com> wrote:
>
> Hello!
>
> I'm trying to find out if there's any way to evaluate a Lua expression and then capture the result from C.
>
> For instance, if I had the string "3 * 5", would there be any way to pass this to Lua (along with a lua_State) and
> recover the result of this operation?

First, you must understand that when you execute Lua code, it is
executed/loaded as though it were a function [1]. Say you load "5 +
5", it's equivalent to:

local f = function(...) 5 + 5 end; return f;

Not to say that compiles; in fact it won't compile. You see, if you
want results from the Lua expression, you must prepend "return " to
the Lua code. Of course, this only works if what you are executing
_is_ a simple expression (or expression list). Assuming you now
understand this, you only need to use lua_call [2] with the proper
arguments and the amount of return values you expect back.

[1] http://www.lua.org/manual/5.1/manual.html#luaL_loadstring
[2] http://www.lua.org/manual/5.1/manual.html#lua_call

HTH,

-- 
-Patrick Donnelly

"One of the lessons of history is that nothing is often a good thing
to do and always a clever thing to say."

-Will Durant