Accessing Functions through the Stack

  • Functions from a lua file can be accessed through the stack
    • The file with the functions is loaded first
The basic steps to access a function are the following
  1\. Load the file with the function
  2\. Use lua_getglobal(L, "functionName") to load the function reference onto the stack
  3\. Push the arguments onto the stack with the first argument going on first etc.
     Note that this means that the first argument is the furthest down on the stack
     if several arguments are being passed
  4\. Call lua_pcall(L, ParameterNum, resultsNum, 0) which executes the function and
     pushes the results onto the stack
  5\. Test that the correct result types are on the stack using lua_isnumber etc.
  6\. Get the results from the stack using lua_tostring etc.
  7\. Pop the stack using lua_pop to put the function and arguments from the stack
```

_An example of the code to execute a Lua function from C code_

```

#include 
#include 
#include 
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"

#define MAX_COLOR 255
char *load (lua_State *L, const char *fname, int *number, int x, int y, char* myString);

int main(void) {
    lua_State *L = luaL_newstate();   /* opens Lua */
    luaL_openlibs(L);             /* opens the standard libraries */
    char filename[] = "C:/Lua C and C++/workspace/functionFile.lua";
    int number = 0;
    int x = 5;
    int y = 6;
    char *a = malloc(100);
    strcpy(a, "Hello to ");
    char * resultString = load(L, filename, &number, x, y, a);

    printf("number is %d\n", number);
    printf("The String is %s\n",  resultString);
    free(a);
    free(resultString);
    return 0;
}

char *load (lua_State *L, const char *fname, int *number, int x, int y, char* myString) {

    if (luaL_loadfile(L, fname) || lua_pcall(L, 0, 0, 0)) {
        luaL_error(L, "cannot run config file: %s", lua_tostring(L, -1));
    }

    lua_getglobal(L, "modifyData");
    lua_pushnumber(L, x);
    lua_pushnumber(L, y);
    lua_pushstring(L, myString);

    if (lua_pcall(L, 3, 2, 0) != 0) {
        luaL_error(L, "error in function ");
    }

    int z = lua_tointeger(L, -2);
    printf("the number is %d\n", z);
    *number = z;

    myString = lua_tostring(L, -1);
    printf("the string is %s\n", myString);

    lua_pop(L, 1);
    lua_pop(L, 1);
    return myString;
}
```

_The Lua file with a function looked like the following_

```

function modifyData(x, y, theString)
   theString = theString .. "the world"
   return x*y , theString
end
```

*   Errors can be handled either by the C code or by calling LuaL_error(L, errorMessage);