I'm calling a C++ function(print_no) defined in a shared object file from my lua module. The C++ function takes the argument passed from lua and uses it to initialise the static variable.
I was expecting that when this function will be called multiple times, the variable will retain the value it got during the first time it was called. This is my current understanding about static variables inside a function.
Here's my C++ code(test.cpp)
extern "C"
{
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
}
static int print_no(lua_State *L)
{
static double d = lua_tonumber(L, 1); /* get argument */
return 1; /* number of results */
}
static const struct luaL_Reg mylib [] =
{
{"print_no", print_no},
{NULL, NULL} /* sentinel */
};
extern "C"
{
int luaopen_mylib (lua_State *L)
{
luaL_register(L, "mylib", mylib);
return 1;
}
}
I make a .so file using the following command:
g++ -shared -o mylib.so test.cpp -fPIC
Given below is my lua code(module.lua)
temp = require "mylib"
print(temp.print_no(5))
print(temp.print_no(6))
Given below is the output when I run this module:
[vishal@localhost test]$ lua -v
Lua 5.1.4 Copyright (C) 1994-2008 Lua.org, PUC-Rio
[vishal@localhost test]$ lua module.lua
5
6
I was expecting that both the times 5 will be printed. What's wrong with my understanding?
5? you just always pass one argument to theprint_nofunction, so it prints this argument :) - Raffallo