I created a SWIG typemap for my function.
%typemap(in) (int width, int height, lua_State *L)
{
if (!lua_isnumber(L, -1) || !lua_isnumber(L, -2))
SWIG_exception(SWIG_RuntimeError, "argument mismatch: number expected");
$1 = lua_tonumber(L, -1);
$2 = lua_tonumber(L, -2);
$3 = L;
}
But it doesn't work if I try to call the function in Lua.
I call this function like the following in Lua.
createWindow(500,300)
I just want to pass width
, height
from Lua to this function.
How can I fix the typemap to make it work?
Multi-argument typemaps won't do the trick here because they are designed to map a single Lua argument to multiple C++ arguments. You can help yourself with a default argument here. This is done using %typemap(default)
. We tell SWIG to default any lua_State *L
argument to the instance used by SWIG.
%module window
%{
#include <iostream>
void createWindow(int width, int height, lua_State *L) {
std::cout << "Creating window of size " << width << "x" << height << '\n'
<< "Number of arguments: " << lua_gettop(L) << '\n';
}
%}
%typemap(default) (lua_State *L) {
$1 = L;
}
void createWindow(int width, int height, lua_State *L);
local window = require("window")
window.createWindow(500,300)
$ lua5.2 test.lua
Creating window of size 500x300
Number of arguments: 2