sol2 icon indicating copy to clipboard operation
sol2 copied to clipboard

Quick Question

Open LedLoaf opened this issue 4 years ago • 1 comments

Hello,

I had asked this question before, but I think it might have been removed since it was probably considered easy to do. For the future I'd love to know of a tutorial example that shows this. I'll copy down the answer this time as well.

luafile.lua return { width = 200, height = 15, tilewidth = 32, tileheight = 32, }

What I'm trying to do is parse the table, without manually assigning the table, such as changing return to Map = { .... }. Which is easy to parse at that point, but doing it with the return type has never worked.

sol::state lua;
// open some common libraries
lua.open_libraries(sol::lib::base, sol::lib::package);
lua.script_file("luafile.lua");
sol::table self = lua["Return"];
auto v = self["width"];
std::cout << "Width: " << v.get_or(0) << "\n";

From what I recall I was told to basically do this. But I'm pretty sure using return wasn't needed. You could just simply ignore it and call it still. Any help would be appreciated.

EDIT: This might look more simplified to see what I'm trying to do.

```sol::state lua;
// open some common libraries
lua.open_libraries(sol::lib::base, sol::lib::package);
lua.script_file("return {width = 200,height = 15,tilewidth = 32,tileheight = 32,nextlayerid = 7,nextobjectid = 9 }");

int v = lua["width"].get_or(0);
std::cout << v;```

Output: 0

Also: I'm using Sol from vcpkg.

EDIT2================== Okay, I figured it out. Geez, I continue to make this harder than it needs to be.

	sol::state lua;
	lua.open_libraries(sol::lib::base);
	// load and execute from file
	const sol::load_result script = lua.load_file("luafile.lua");
	if (!script.valid()) {
		const sol::error error = script;
		const std::string errorMsg = error.what();
	
		return false;
	}
	auto file = lua.script_file("luafile.lua");
	sol::table table = file;
	std::string v = table["version"];
	std::cout << v<<"\n";

With that said I'll simply just ask if there is a better way to do this cleanly just to make sure there isn't another way. Much appreciated.

LedLoaf avatar Nov 10 '21 06:11 LedLoaf

You should be able to do it in a way similar to this:

sol::state lua;
lua.open_libraries(sol::lib::base, sol::lib::package);
sol::table result = lua.script("return {width = 200,height = 15,tilewidth = 32,tileheight = 32,nextlayerid = 7,nextobjectid = 9 }");

int v = result["width"].get_or(0);
std::cout << v;

You can basically interpret the return value of either .script() or .script_file() as a table (since that's what your script is returning) and then use that to access the values you care about.

OrfeasZ avatar Nov 12 '21 18:11 OrfeasZ