Use C++ and Lua to transfer custom data types to each other

Use C++ and Lua to transfer custom data types to each other

In the interaction between C++ and Lua language, it is often necessary to pass custom data types. This article will introduce how to transfer structures between C++ and Lua.

We first need to define a structure in C++ and add some member variables to it:

struct UserInfo {
    std::string name;
    int age;
    double balance;
};

Next, to introduce the structure defined in C++ in Lua, you can use tolua++ to generate the corresponding header file. In Lua scripts, we can use the classes and methods in the header files generated by tolua++ to easily access the structures and methods defined in C++.

The following is the code to generate the header file using tolua++:

#ifdef __cplusplus
extern "C" {
#endif
#include "tolua++.h"
#ifdef __cplusplus
}
#endif

#include "UserInfo.h"

TOLUA_API int register_all_UserInfo(lua_State* tolua_S)
{
    tolua_open(tolua_S);
    tolua_usertype(tolua_S,"UserInfo");
    tolua_cclass(tolua_S,"UserInfo","UserInfo","",nullptr);
    tolua_beginmodule(tolua_S,"UserInfo");
        tolua_variable(tolua_S,"name", &UserInfo::name, nullptr );
    

Guess you like

Origin blog.csdn.net/qq_33885122/article/details/132484974