www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - bindbc-lua :: Return tables from D

reply luaaaa <dummy dummy.org> writes:
Hi. I got a problem when I used bindbc-lua. I wanna return Lua 
table by D function like this:

**Simple example (Working)**
```
import std.stdio:writeln;
import std.conv:to;
import bindbc.lua;

void main() { // dmd 2.097.2 x64 on Mac & LUA_51, static
	lua_State *L = luaL_newstate();
     luaL_openlibs(L);
	string str = `print("Sup! I'm Lua!")`;
	luaL_loadbuffer(L, cast(const(char)*)str, str.length, "line");
	int error = lua_pcall(L, 0, 0, 0);
	if(error !=0)
		writeln(lua_tostring(L, -1).to!string); // Working fine
}
```

**Return Lua's table by D function (Can't compile it)**
```
import std.stdio:writeln;
import std.conv:to;
import bindbc.lua;

void main() { /* dmd 2.097.2 x64 on Mac & LUA_51, static */
	lua_State *L = luaL_newstate();
     luaL_openlibs(L);
	luaL_register(L, cast(const(char)*)"funcD", test);
	string str = `x = funcD()`;
	luaL_loadbuffer(L, cast(const(char)*)str, str.length, "line");
	int error = lua_pcall(L, 0, 0, 0);
	if(error !=0)
		writeln(lua_tostring(L, -1).to!string);
}

static int test(lua_State* L) {
	lua_newtable(L); // Make new table => [0:test_data]
     lua_pushstring(L, cast(const(char)*)"0");
     lua_pushstring(L, cast(const(char)*)"test_data");
     lua_settable(L, -3);
     return 1;
}
```

Please any advise me. Thanks!
Sep 25 2021
parent russhy <russhy gmail.com> writes:
bindbc-lua expect the function to be  nothrow


This should work:

```D
import std.stdio : writeln;
import std.conv : to;
import bindbc.lua;

void main()
{
	lua_State* L = luaL_newstate();
	luaL_openlibs(L);
	lua_register(L, "funcD", &test);
	string str = "x = funcD()";
	luaL_loadbuffer(L, str.ptr, str.length, "line");

	int error = lua_pcall(L, 0, 0, 0);
	if (error != 0)
		writeln(lua_tostring(L, -1).to!string);
}

nothrow int test(lua_State* L)
{
	lua_newtable(L);
	lua_pushstring(L, "0");
	lua_pushstring(L, "test_data");
	lua_settable(L, -3);
	return 1;
}

```
Sep 25 2021