3

I have some functions declared and initialized in .lua file. Then, when I receive signal, I read string_t variable with the name of function to call from file. The problem is that I don't know how to push function to stack by its name or call it.

For example:

test.lua

function iLoveVodka()
    --some text
end

function iLoveFish()
    --another text
end

C File:

string_t a = "iLoveVodka()"

How can i call function from C/C++ code iLoveVodka() only by having its name?

4
  • push it on the stack and then call lua_pcall Commented Jun 16, 2014 at 20:01
  • @Appleshell which function do I have to use to push it into stack? Commented Jun 16, 2014 at 20:02
  • 2
    If it's a global funciton, lua_getglobal(state, "iLoveVodka");, or alternatively push its name on the stack and call lua_getfield. (Don't be afraid to explore around lua.org/manual/5.1/#index ) Commented Jun 16, 2014 at 20:06
  • 1
    Also, if you have a chunk of runnable code (like iLoveVodka()) as opposed to just the name of the function you can use luaL_dostring or the functions it is a macro around to run that chunk of code. Commented Jun 17, 2014 at 2:06

1 Answer 1

1

Here is some sample code that does two things:

  • Loads the file "test.lua" from the same directory.
  • Tries to call the function iLoveVodka(), if it can be found.

You should be able to build this easily enough:

  #include <lua.h>
  #include <lauxlib.h>
  #include <lualib.h>
  #include <stdio.h>
  #include <stdlib.h>


   int main( int argc, char *argv[])
   {
      lua_State *l = luaL_newstate ();
      luaL_openlibs (l);

      int error = luaL_dofile (l, "test.lua");
      if (error)
      {
          printf( "Error loading test.lua: %s\n",luaL_checkstring (l, -1) );
          exit(1);
      }

      /**
       * Get the function and call it
       */
      lua_getglobal(l, "iLoveVodka");
      if ( lua_isnil(l,-1) )
      {
          printf("Failed to find global function iLoveVodka\n" );
          exit(1);
      }

      lua_pcall(l,0,0,0);

      /**
       * Cleanup.
       */
      lua_close (l);

      return 0;
  }

This can be compiled like this:

 gcc -O -o test `pkg-config --libs --cflags lua5.1`  test.c

Just define your iLoveVodka() function inside test.lua, and you should be OK.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.