2
votes

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?

1
why both times 5? you just always pass one argument to the print_no function, so it prints this argument :) - Raffallo

1 Answers

5
votes

You aren't pushing your result back onto the lua stack so lua is simply reading the next value on the stack which is the argument you passed to print_no.

Try:

static int print_no(lua_State *L)
{
  static double d = lua_tonumber(L, 1); /* get argument */
  lua_pushnumber(L, d);
  return 1; /* number of results */
}