Lua Tutorial (20): Lua calls C function

Source: Internet
Author: User
Tags first string lua require

The ability of LUA to invoke C functions will greatly improve the scalability and usability of Lua. For some operating system-related functions, or for modules with high efficiency requirements, we can do this with the C function, and then invoke the specified C function via Lua. For those C functions that can be called by LUA, their interfaces must be in the form of LUA requirements, typedef int (*lua_cfunction) (lua_state* L). Simply stated, the function type contains only a pointer to the LUA environment as its only parameter, which the implementation can use to further obtain the actual arguments passed in the LUA code. The return value is an integer indicating the number of return values that the C function will return to the LUA code, or return 0 if there is no return value. It is necessary to note that the C function cannot directly return the true return value to the LUA code, but instead passes the call parameters and return values between the LUA code and the C function through the virtual stack. Here we will describe two rules for LUA calling C functions.

1. The C function acts as part of the application.


#include <stdio.h>
#include <string.h>
#include <lua.hpp>
#include <lauxlib.h>
#include <lualib.h>
C Registration function to be called by Lua.
static int add2 (lua_state* L)
{
Check that the arguments in the stack are valid, that 1 represents the first parameter (left to right) when Lua is called, and so on.
If the LUA code passes a parameter that is not number when it is called, the function will error and terminate the execution of the program.
Double OP1 = Lual_checknumber (l,1);
Double OP2 = Lual_checknumber (l,2);
Presses the result of the function into the stack. If there is more than one return value, it can be pressed into the stack multiple times.
Lua_pushnumber (L,OP1 + OP2);
The return value is used to prompt the number of return values for the C function, which is the number of return values in the push-in stack.
return 1;
}
Another C-registered function to be called by Lua.
static int sub2 (lua_state* L)
{
Double OP1 = Lual_checknumber (l,1);
Double OP2 = Lual_checknumber (l,2);
Lua_pushnumber (L,OP1-OP2);
return 1;
}
Const char* TestFunc = "Print (ADD2 (1.0,2.0)) print (Sub2 (20.1,19))";
int main ()
{
lua_state* L = Lual_newstate ();
Lual_openlibs (L);
Registers the specified function as a global function variable for LUA, where the first string parameter is the LUA code
The global function name used when invoking the C function, and the second argument is a pointer to the actual C function.
Lua_register (L, "Add2", ADD2);
Lua_register (L, "Sub2", SUB2);
After registering all of the C functions, you can use these already registered C functions in the LUA code block.
if (lual_dostring (L,testfunc))
printf ("Failed to invoke.\n");
Lua_close (L);
return 0;

}

2. The C function library becomes a module of Lua.

Code-generation library files that contain C functions, such as Linux so, or Windows DLLs, are copied to the current directory where the LUA code resides, or to the directory that the LUA_CPATH environment variable points to, so that the LUA parser can locate them correctly. In my current Windows system, I copy it to "C:\Program files\lua\5.1\clibs\", which contains all C libraries that Lua can invoke. See the following C language code and key notes:


#include <stdio.h>
#include <string.h>
#include <lua.hpp>
#include <lauxlib.h>
#include <lualib.h>
The C function to be registered, the Declaration form of the function is given in the example above.
It is important to note that the function must be exported in the form of C, so extern "C" is required.
The function code is the same as the previous example and is not mentioned here.
extern "C" int Add (lua_state* L)
{
Double OP1 = Lual_checknumber (l,1);
Double OP2 = Lual_checknumber (l,2);
Lua_pushnumber (L,OP1 + OP2);
return 1;
}
extern "C" int sub (lua_state* L)
{
Double OP1 = Lual_checknumber (l,1);
Double OP2 = Lual_checknumber (l,2);
Lua_pushnumber (L,OP1-OP2);
return 1;
}
The first field of the Lual_reg struct is a string that is used to notify Lua of the name of the function at registration time.
The first field is a C function pointer.
The two fields of the last element in the struct array are null to indicate that the LUA registration function has reached the end of the array.
Static Lual_reg mylibs[] = {
{"Add", add},
{"Sub", sub},
{NULL, NULL}
};
The only entry function for the C library. Its function signature is equivalent to the registration function above. See below for a few notes:
1. We can simply understand this function as the factory function of the module.
2. Its function name must be luaopen_xxx, where xxx represents the library name. The LUA code require "XXX" needs to correspond to it.
3. In Lual_register's invocation, its first string argument is the module name "XXX" and the second parameter is an array of functions to be registered.
4. It is important to emphasize that all code that needs to use "XXX", whether C or LUA, must be consistent, which is the LUA Convention,
Otherwise, it cannot be called.
extern "C" __declspec (dllexport)
int Luaopen_mytestlib (lua_state* L)
{
Const char* libname = "Mytestlib";
Lual_register (L,libname,mylibs);
return 1;

}

See the following LUA code: Require "Mytestlib"--Specifying the package name
--when called, it must be package.function
Print (Mytestlib.add (1.0,2.0))
Print (Mytestlib.sub (20.1,19))


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.