sol2 icon indicating copy to clipboard operation
sol2 copied to clipboard

Lua class inheriting user_type

Open JTAG7371 opened this issue 4 years ago • 0 comments

So i am trying to make a mini user interface via lua and sol2 seems to be the cleanest approach to interact between C and lua.

Basically i am trying to make a usertype that allows me to call functions in my C code from lua as well as then inherit from an element class in lua, The issue is i cannot seem to inherit as when i try calling getmetatable it complains about a nil value.

struct JUIElement
{
	const char* name;
};

JUIElement* JUI_LuaCall_ConstructJUIElement()
{
	printf("Allocating new JUI Element\n");
	auto* new_element = new JUIElement();
	new_element->name = "test_ignore";
	return new_element;
}

void JUI_LuaCall_SetupUIImage(JUIElement* element)
{
	printf("Called with element: 0x%p\n", element);

	if (element)
	{
		printf("%s\n", element->name);
	}
}

int main()
{
	sol::state lua;

	sol::usertype<JUIElement> utype = lua.new_usertype<JUIElement>("JUIElement");

	utype["setupUIImage"] = &JUI_LuaCall_SetupUIImage;
	lua["ConstructJUIElement"] = JUI_LuaCall_ConstructJUIElement;

	auto result = lua.script_file("test.lua");
	if (result.valid())
	{
		printf("Success\n");
	}
	else
	{
		sol::error err = result;
		std::string what = err.what();
		printf("ERROR: %s\n", what.data());
	}
	return 0;
}

That is the C code for my project, its very basic and JUIElement was just a crude test but will only contain data that should not be accessed via lua

JUI = {}

local registerVal1 = {}
registerVal1.id = "JUIElement"

JUI.UIElement = { id = "JUIElement" }
JUI.UIElement.__index = JUI.UIElement

function JUI.UIElement.setClass(elem, type)
	if arg0 ~= nil then
		local elem_meta_table = getmetatable(elem)
		local new_index_table = getmetatable(elem_meta_table.__newindex)
		if not new_index_table then
			local new_index = {}
			new_index.__index = type
			setmetatable(registerVal2.__newindex, new_index)
		else
			new_index.__index = type
		end
	end
end

function JUI.UIElement.new()
    local new_elem = ConstructJUIElement()
    JUI.UIElement.setClass(new_elem, JUI.UIElement)
    return new_elem
end

function JUI.UIElement.test_inheritance(arg0)
	print("Test Inheritance!")
end

test_element = JUI.UIElement.new()
test_element:setupUIImage()

This is my lua code that i think should do the job. I am very much new to lua.

image

Sorry if i am not making sense, I dont really know fully what im doing

SORRY i forgot to open libraries. After doing this though i now have this error: image

JTAG7371 avatar May 04 '21 12:05 JTAG7371