MoustacheSpy
MoustacheSpy

Reputation: 763

Creating a new c++ object from within a lua script?

---Context---

I want to have a class called "fileProcessor". This class is completely static and merely serves as a convinient namespace (within my normal library namespace) for some global function. This is a basic blueprint of the class with only the relevant stuff

class fileProcessor{
private:
    lua_State* LUA_state;
public:
    static std::variant<type1,type2> processFile(const char* filePath,const char* processorScript);
}

Please note again that I ommitted most of the stuff from the class so if anything seems odd ignore it.

What process file is supposed to do is:

  1. Read the filePath file, storing all directives including it (this is my own filetype or style of syntax. This is already handeled correctly). The directives are stored with strings, one for the command and one for everything after it.
  2. Read the script file and check if it has a commented out fileProcessor line at the top. This is to make sure that the lua script loaded is relevant and not some random behaviour script
  3. Load and compile the lua script.
  4. Make all read directives available (they are saved in a struct of 2 strings as mentioned before)
  5. Run the file and recieve a object back. The object should only be of types that I listed in the return type (variant)

I am having problems with step 4 and one vital part of the scripting.

---Question---

How can I make the creation of a full new object of type1 or type2 possible within lua, write to it from within lua and then get it back from the lua stack into c++ and still know if its type1 or type2?

---No example provided since this question is more general and the only reason I provided my class is for context.---

Upvotes: 2

Views: 1644

Answers (1)

Griffin
Griffin

Reputation: 766

It seems like you are trying to do it the other way around. I quote a part of this answer:

...you are expecting Lua to be the primary language, and C++ to be the client. The problem is, that the Lua C interface is not designed to work like that, Lua is meant to be the client, and all the hard work is meant to be written in C so that Lua can call it effortlessly.

If you are convinced there is no other way that doing it other way around you can follow the workaround that answer has given. Otherwise I think you can achieve what you need by using LUA as it meant to be.

LUA has 8 basic types (nil, boolean, number, string, userdata, function, thread, and table). But you can add new types as you require by creating a class as the new type in native C++ and registering it with LUA.

You can register by either:

  1. Using some LUA helper for C++ like luna.h (as shown in this tutorial).
  2. Pushing a new lua table with the C++ class (check this answer).

Class object instance is created in your native C++ code and passed to LUA. LUA then makes use of the methods given by the class interface.

Upvotes: 2

Related Questions