Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How do I create a table from C++? #170

Open
vinniefalco opened this issue Jan 6, 2017 · 3 comments
Open

How do I create a table from C++? #170

vinniefalco opened this issue Jan 6, 2017 · 3 comments

Comments

@vinniefalco
Copy link

Its not clear to me how to create a table in the Lua environment from C++...

@sebt3
Copy link

sebt3 commented Jan 6, 2017

So far i'm doing this :

state("a={}");
for(std::vector<uint32_t>::iterator i = a->begin();i!= a->end();i++) {
	std::string cmd = "table.insert(a,"+std::to_string(*i)+")";
	state(cmd.c_str());
}

But I'ld love a better way, indeed :)

@vinniefalco
Copy link
Author

Oh my...that's awful! lol

@kharyus
Copy link

kharyus commented Feb 19, 2017

I was experimenting the following, although I'm unsure whether or not I'm going to use this code in my project:

int counter = 0;
// ...
state(std::string("x" + std::to_string(++counter) + " = Object:new()").c_str());
sel::Selector tableReference = state[std::string("x" + std::to_string(counter)).c_str()];

Here I call a user-defined new method from a Lua do_string that contains the x char and concatenate it into a counter that tells how many tables have been instantiated in the program so that they may have unique identifiers.
I don't care about the identifier since at least in my project I'm never going to call them directly. I only use this identifer so that lua may own the table. Ideally I would want to store it directly in C++ and have lua only reference it, but I don't know how I would accomplish that.
Then when it's time to free the memory, set the table to nil.

My first solution was creating a Lua VM for each instance of my table since each VM maintains its own state. I was not sure if creating many VMs is going to have a significant impact on performance so I played it safe by looking for other ways. The big advantages here were that the states were self-contained, there was no need for manual memory handling and the code just looked better. Oh well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants