C++ and Lua interaction tutorials (based on LuaBridge)

Original October 31, 2017 14:19:39

Author: Cha Zhiwang, a front-end developer of sunflower remote control software.

Recently, the company needs to do a sunflower remote control software for cross platform project, code reusability, embedded cross platform scripting language, we chose Lua, the reason is that Lua C prepared by the standard in almost all operating system and platform can be compiled, Lua scripts can easily be C/C++ code calls. You can turn call C/C++ function, today I share with you some problems under the c++ and Lua interaction.

In order to facilitate the interaction between c++ and Lua, I introduced LuaBridge. Because it is simple and easy to use source code, only the first file, no.Cpp files, do not need to compile, only need to refer to the header file, convenient and quick.

Next, I wrote an example of the Win32 console project with the VS2008 tool to explain the simple intermodulation of c++ and Lua.

1. Preparation work

Download the latest from the Lua websiteHttp://www.lua.org/download.htmlThe next lua-5.3.4.tar.gz can be directly compiled into lib or directly added to the project after decompressing it. I put it directly into the project. When I compile, there will be multiple main function entry errors (remove the corresponding files).

Download LuaBridge, download address:Https://github.com/vinniefalco/LuaBridgeThe Source/LuaBridge under the list is the source code, and Manual.html is the help document.

Create the Win32 console project test_lua to put Lua source and LuaBridge header files into the project directory and add to the project project.

Two. Write code

1. First, the Lua and LuaBridge header files are quoted as follows:

/ / references the C file header file so you need to add extern "C"
Extern"C"
{
     #include"Lua.h"
     #include"Lauxlib.h"
     #include"Lualib.h"
}
#include"LuaBridge\LuaBridge.h"

2, then create the test_lua class and a subclass code as follows:

ClassTest_lua
{
Public:
Test_lua ()
{
M_test_string ="C++ test string";
}
~test_lua ()
{
}
//test method
    Void(testIntA,IntB)
{
        Printf("C++ test function%d+%d=%d\n"A, B, a+b);
}

/ / set attribute method
    VoidSetName (STD::StringName)
{
M_name = name;
}
Attribute / / get method, attention to the need to add const
    STD::StringGetName ()Const
{
        ReturnM_name;
}
/ / call for Lua method, return multiple parameter method
    IntCFunc (lua_State* L)
{
/ / return parameter 1
Lua_pushstring (L,"Str1");
/ / return parameter 1
Lua_pushstring (L,"Str2");
Return / / the number of parameters
        Return Two;
}
    STD::StringM_test_string;
    STD::StringM_name;
    Static IntM_static_data;
};
//test_lua static variable definition (static variable is only declared in a class)
IntTest_lua:: m_static_data;
//test_lua subclass
ClassTest_lua_child:PublicTest_lua
{
    Public:
Test_lua_child (STD::StringTest)
M_test_child_string (test)
{
            Printf("Call test_lua_child constructor\n");
}
~test_lua_child ()
{
}
        STD::StringM_test_child_string;
};

3, create a Lua script file a.lua content:

--lua print Lua script
Print("Lua script")
- call the member variable m_test_string (test_str is a registered name)
Print(test_lua.test_str)
- call the c++ static variable (need to add the test namespace)
Test.test_lua.static_data=Twelve
Print("Static_data:"..Test.test_lua.static_data)
- call the c++ class test_lua property name
Test_lua.name="Name_property";
Print("Name:"..Test_lua.name);
--lua calls the c++ method test_lua as the registration name of the c++ class in Lua, and calls the test method
Test_lua:test (Three,Four)

- - call the c++ call method to return multiple values
LocalRet1, ret2 = test_lua:cFunc ()
Print("Ret1="..Ret1.."Ret2="..Ret2)

- creating test_lua_child objects
LocalTest_lua_child = test.test_lua_child ("Test_string")
- call its variables
Print("Child string:"..Test_lua_child.test_child_string);
- call the name property of the parent class
Test_lua_child.name="Child_name_property";
Print("Name:"..Test_lua_child.name);

--lua method addition
Function Lua_add_function(a, b)
    Print("Lua_add_function")
    ReturnA+b;
End

--lua method string addition (.. additive syntax)
Function Lua_add_str_function(a, b)
    Print("Lua_add_str_function")
    ReturnA..B;
End

4. Write the main function

4.1, the initialization of Lua and the basic library for loading Lua

/ / initialize Lua (last remember to call LuA_close(LuA_state) release)
LuA_State* LuA_state= luaL_newstate ();
Loading / / Lua basic library
LuaL_openlibs (LuA_state);

4.2. Register in Lua with luabridge

It is important to note here that multiple class registration needs to add a namespace (test), and.EndClass () does not add a semicolon

Luabridge:: getGlobalNamespace(lua_state)
        .BeginNamespace ("Test")
        .BeginClass<Test_lua>("Test_lua")
        .AddConstructor<Void(*()Void)>()/ / no args constructor registration
        .AddData ("Test_str",&Test_lua:: m_test_string)/ / register variables to Lua
        .AddStaticData ("Static_data",&Test_lua:: m_static_data)/ / registered static variables to Lua
        .AddFunction ("Test",&Test_lua:: Test)/ / registration test, to the Lua (addStaticFunction static registration function is similar)
        .AddProperty ("Name",&Test_lua:: GetName,&Test_lua:: SetName)The registration method (addStaticProperty / attribute static properties are similar)
        .AddCFunction ("CFunc",&Test_lua:: cFunc)Registered / / return multiple parameters to the Lua method
        .EndClass ()
        .DeriveClass<Test_lua_child, test_lua>("Test_lua_child")/ / sub class registration
        .AddConstructor<Void(*(STD):: String)>()There is / / constructor registration
        .AddData ("Test_child_string",&Test_lua_child: m_test_child_string)/ / register variables to Lua
        .EndClass ()
        .EndNamespace ();

/ / create a test_lua object
Test_lua test;
Luabridge:: setGlobal(lua_state,&Test,"Test_lua");/ / registered test_lua object to Lua

Note: test_lua can also be created in Lua, because constructor is also registered to Lua, such as test.test_lua (), and the a.lua script above has sub class test_lua_child's creation and calling property method of its parent class.

4.3, after completing the registration, return to read the a.lua script written above, we will know the meaning of each call, add and run the Lua script code, and execute the code as follows:

    / / run Lua scripts
LuaL_dofile (lua_state,"A.lua");
/ / close Lua
Lua_close (lua_state);
The result of the compilation execution is:
Lua script
C++ testString
Static_data:Twelve
Name: name_property
C++ testFunction Three+Four=Seven
Ret1=str1 ret2=str2
Call test_lua_child constructor
ChildString: test_string
Name:child_name_property

4.4, c++ calls the Lua method, because Lua method is the same as function parameter and is a return value. For convenience, template form (taking two parameters as an example) is used. The first parameter (Lua object) and second parameter (method name) are fixed.

Template<TypenameR,TypenameT1,TypenameT2>
R call (LuA_State* LuA_stateConst char* name, T1 arg1, T2 arg2)
{
/ / read method
LuA_getglobal(LuA_stateName);
/ / judgment is not a method
    If(luA_isfunction(LuA_state-.One))
{
/ / press parameters
Luabridge:: Stack<T1>::Push (LuA_stateArg1);
Luabridge:: Stack<T2>::Push (LuA_stateArg2);
(/ / execute the function parameters for the Lua object, the number of parameters and the return value of the number of return)
LuA_pcall(LuA_state,Two,One,Zero);
}
/ / get a return
Return luabridge:: Stack<R>:Get (LuA_state-.One);
}
After running the Lua script, add the following call code:
/ / call the Lua method LUA_add_function
Int RET = call<int> (LuA_state,"Lua_add_function",Five,Six);
/ / call the Lua method LUA_add_str_function
Std:String value = call<const char*> (LuA_state,"Lua_add_str_function","5","6");
Printf ("Lua_add_function result:%d\n"RET).;
Printf ("Lua_add_str_function result:%s\n"Value.c_str ());

The result of the compilation execution is:

LuaScript
C++ testString
Static_data:Twelve
Name: name_property
C++ test functionThree+Four=Seven
Ret1=str1 ret2=str2
Call test_lua_child constructor
ChildString: test_string
Name: child_name_property
Lua_add_function
Lua_add_str_function
Lua_add_functionResult:Eleven
Lua_add_str_functionResult:Fifty-six

4.5. Finally, talk about luaL_dostring

LuaL_dostring with luaL_dofile is a role that is loaded and run the Lua script, just a different object, see the name to know is a method to load the file, the other one is loading string, finally running inside the Lua script, luaL_dostring in Lua embedded into the often used other scripting language, now use the above examples of additional code before the lua_close simple explanation:

Definition / / Lua script, name calls the test_lua class attribute in and print it out
Std:String LuA_string="Print (\")Run Lua string test_lua name:\"..Test_lua.name" ";
/ / loaded and run string
LuaL_dostring (LuA_stateLu.A_string.c_str ());
The results of the compilation run are:
Run Lua string test_lua name:Name_property

When it comes to the embedding problem, now the sunflower remote control software to do the interface using XML, here involves Lua embedded in the XML, because of the characteristics of lua, XML in these other systems can be used, so you will never have to worry about adding a new interface of each system have again set, Lua embedding principle XML is the Lua script into a node such as:

<Script><![CDATA[
--lua代码
print("Run Lua script")
]]>< /Script>

It is possible to parse the script node content corresponding to the XML, and then load the run with luaL_dostring.

Finally, with the present sunflower interface map

Sunflower client:
Here's a picture description

Sunflower control end:
Here's a picture description

Three, summary

Hope that through simple examples above can help you quickly get started c++ embedded in the Lua script code can also be seen from the above, Lua and c++ are easy to call each other, Lua and c++ through the operation of virtual stack to interact, such as the above call the Lua method, c++ method is put into the top of the stack, then the Lua value from the top the stack, then the results back to the top of the stack, then the value of c++ from the top of the stack, Lua calls c++ is similar, is the need to call the c++ register to Lua Lua, you can call, want to know more about the basic Lua syntax and the specific principle can view the Lua in the manual.html, the other uses of LuaBridge can also be see LuaBridge manual.html.

Copyright declaration: This article is an original article for the blogger. It is not allowed to be reprinted without the permission of the blogger.

C++ program embedded Lua (based on LuaBridge)

Transfer: https://segmentfault.com/a/1190000005765697 If the configuration file is not fixed, you have to rely on the script. C++ program to block point script, Lua almost is preferred. L...
  • Yuliying
  • Yuliying
  • 2017, 31 03, 2017, 20:35
  • Five hundred and twenty-six

Binding C/C++ objects with LuaBridge for Lua

Recently, in order to summarize the various methods and third party libraries and principles of Lua binding C/C++ objects, we have learned the LuaBridge library for Lua binding C/C++ objects, and the following is the learning note, which essentially translates the Reference Manual of the library basically.
  • Zjq2008wd
  • Zjq2008wd
  • 2016, 02 02, 2016, 11:19
  • Nine hundred

LUA is the first interaction with C++

It has been two weeks to the company. Learning Lua has begun to be used in the project, but the Lua function is basically encapsulated by the company. There is no source code to interact with the two languages. For example, if you register an object with LUA for LUA,...
  • Fengbangyue
  • Fengbangyue
  • 2012, 11 03, 2012, 16:27
  • Twenty-four thousand three hundred and eight

C++ program embedded Lua (based on LuaBridge)

Transfer: https://segmentfault.com/a/1190000005765697 If the configuration file is not fixed, you have to rely on the script. C++ program to block point script, Lua almost is preferred. L...
  • Yuliying
  • Yuliying
  • 2017, 31 03, 2017, 20:35
  • Five hundred and twenty-six

Binding C/C++ objects with LuaBridge for Lua

Recently, in order to summarize the various ways and the third party libraries and principles of Lua binding C/C++ objects, we have learned the LuaBridge library for Lua binding C/C++ objects, and the following is learning notes, which is essentially the Reference of the library. Manual basically translated,...
  • MaximusZhou
  • MaximusZhou
  • 2014, 31 03, 2014, 20:57
  • Seven thousand and ninety-seven

LuaBridge:Lua binding C/C++ objects

Recently, in order to summarize the various methods and third party libraries and principles of Lua binding C/C++ objects, we have learned the LuaBridge library for Lua binding C/C++ objects, and the following is the learning note, which essentially translates the Reference Manual of the library basically.
  • Cbbbc
  • Cbbbc
  • 2015 04 - 19 00:36
  • Nine hundred and eighty-eight

C++/Lua arbitrary parameter mutual invocation of type security

Transfer: http://gulu-dev.com/post/2016-05-19-cpp-lua-vargs When C++ and Lua collaborate, the intermodulation of both sides is an inseparable topic. Normally...
  • Yuliying
  • Yuliying
  • 2017, 05 04, 2017, 11:58
  • Five hundred and sixty-nine

Analysis of the method of C++ binding to Lua

Though binding C++ objects to Lua, libraries such as tolua++, LuaBridge and luabind can be used directly, it is clear that the common way of binding C++ objects to Lua is not only helpful for a deeper understanding of Lua mechanism, but also convenient to modify third.
  • MaximusZhou
  • MaximusZhou
  • 19:52 November 2014, 06
  • Two thousand nine hundred and ninety-four

Lua scripts access Android to use JNI to call local interfaces, problems to be paid attention to

The Lua script to access the Android using JNI to call the local interface, need to pay attention to the problem of Android platform access usually need to use JNI to access the java interface, should pay attention to the following issues: Java interface if static, and is public / / type...
  • Pklll000pp44
  • Pklll000pp44
  • 2016, 28 03, 2016, 14:05
  • Seven hundred and ninety-seven

One of the Lua primer: c/c++ calls Lua

#include //lua header file #ifdef __cplusplus Extern "C" { #include "lua.h" #include #include }...
  • X356982611
  • X356982611
  • 2014, 23 05, 2014, 11:54
  • Fifteen thousand one hundred and three
Content Report
Back to the top
Collector assistant
Bad information report
You report the article:C++ and Lua interaction tutorials (based on LuaBridge)
Reporting reasons:
Reasons for the following:

(at most only 30 words are allowed)