#include "lua-nakh.hxx"
#include <iostream>
#include <unistd.h>
#include <string.h>
void* TheThread(void*);
int SetordaneNakh(lua_State* L) {
return 0;
}
int BastaneNakh(lua_State* L) {
return 0;
}
static luaL_Reg const lua_nakh_library[] = {
{ "SetordaneNakh", SetordaneNakh },
{ "NakheTaazeh", NakheTaazeh },
{ "BastaneNakh", BastaneNakh },
{ nullptr, nullptr }
};
static std::string matne_code;
/* code text, shared table */
int NakheTaazeh(lua_State* L) {
std::cout<<"L1"<<std::endl;
matne_code = lua_tolstring(L, -1, nullptr);
std::cout<<"L2"<<std::endl;
lua_gettable(L, -1);
std::cout<<"L3"<<std::endl;
Thread* thread = new struct Thread;
memset(thread, 0, sizeof(Thread));
thread->L = luaL_newstate();
thread->thread_code = &matne_code;
std::cout<<"L4"<<std::endl;
std::cout<<*thread->thread_code<<std::endl;
std::cout<<"L5"<<std::endl;
lua_pushlightuserdata(L, thread);
std::cout<<"L6: "<<(const void*)thread<<std::endl;
std::cout<<"L7"<<std::endl;
if(pthread_create(&thread->thread, nullptr, TheThread, thread) != 0) {
delete thread;
std::cout<<"Thread error"<<std::endl;
return -1;
}
std::cout<<"L8"<<std::endl;
if(pthread_detach(thread->thread) != 0) {
delete thread;
std::cout<<"Thread error detach"<<std::endl;
return -2;
}
std::cout<<"L9"<<std::endl;
return 1;
}
/*
if (luaL_loadbuffer(L2, (const char *) matne_code->c_str(), matne_code->size(), "thread1-L2") != 0)
{
auto error = lua_tostring(L2, -1);
std::cout<<"loadbuffer() has errors. "<<error<<std::endl;
}
lua_pcall(L2, 0, 0, 0);
std::cout<<"Post()"<<std::endl;
*/
void* TheThread(void* arg) {
std::cout<<"C1"<<std::endl;
struct Thread* thread = (struct Thread*) arg;
std::cout<<"C2: "<<thread->thread_code->c_str()<<std::endl;
//thread->L = luaL_newstate();
lua_State *L = thread->L;
std::cout<<"C3"<<std::endl;
luaL_openlibs(L);
std::cout<<"C4"<<std::endl;
if(luaL_dostring(L, thread->thread_code->c_str()) != 0)//LUA_OK)
std::cout<<"ERROR"<<std::endl;
std::cout<<"C5"<<std::endl;
//if(lua_pcall(L, 0, LUA_MULTRET, 0) != LUA_OK)
// std::cout<<"ERROR pcall"<<std::endl;
std::cout<<"C6"<<std::endl;
std::cout<<"TheThread(): "<<thread->thread_code->c_str()<<std::endl;
return nullptr;
}
int luaopen_nakh(lua_State* L) {
//luaL_newlib(L, lua_nakh_library);
luaL_register(L, "lua-nakh", lua_nakh_library);
return 1;
}