lua-users home
lua-l archive

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

On Apr 2, 2008, at 11:43 PM, Shmuel Zeigerman wrote:

Eugen-Andrei Gavriloaie wrote:
Is there a method of evaluating an expression in the present lua context? Here is what I want: lua_evaluate_expression(L,"applications[2].type"); // expect to find `mysql` string pushed into the stack after this call
lua_evaluate_expression(L,"#applications"); // expect to find value of 2 pushed into the stack after this call
This is supposed to push the result of the expression into the stack.

The following is not very efficient, but seems to do what you want
(not tested; error checks to be added):

void lua_evaluate_expression(lua_State *L, const char *expr) {
 lua_pushfstring(L, "return %s", expr);
 luaL_loadstring(L, lua_tostring(L,-1));

Thank you for your quick response but I have 3 questions:


lua_pushfstring(L, "return %s", expr);

Are used only for appending `return ` in front of the expression, right?


The lua_State *L will be reused (I need to read many things), so the end result script from memory will look like this after this sequence of calls from c++

--begin C++ code--
--end C++ code--

--begin lua script represented from lua_State *L point of view --

... (original code from the file that was loaded from the very beginning)

return #applications --this was added by the first call of lua_evaluate_expression

return applications[1] --this was added by the second call

--end lua script represented from lua_State *L point of view --

So, on the second lua_evaluate_expression call from C++ I will have a value of 2 instead of the string 'mysql' pushed on the stack because the entire script execution stops at the first return. Am I right?

3. I think the entire script will be executed entirely on each lua_evaluate_expression because of lua_pcall(L,0,1,0). This is not acceptable because I want to use this approach on other occasions. Here is ok, because we have to deal with a configuration file, but I will definitively have to deal with other types of Lua scripts that are not supposed to run over and over again. Am I right?