Lua calls C function

Source: Internet
Author: User

The main advantage of LUA as an embedded language is that it is very useful to call the C function with C, which can greatly enrich the development ability of LUA by introducing C Dynamic library into the C functions.

How Lua invokes the C function:

1.Lua can call C function, not that LUA can invoke all C functions, just like C calls Lua, need to follow a certain protocol, LUA can only invoke the registered C function, and also through the virtual stack implementation.

2. The registered C function needs to be fulfilled in the form of:

typedef int (*lua_cfunction) (Lua_state *l);
Cases:


Double Max (double A, double b) {
Return a>b? A:B;
}

static int L_max (Lua_state *l) {

Double NUM1 = Lua_tonumber (L, 1);
Double num2 = Lua_tonumber (L, 2);
Lua_pushnumber (L, Max (NUM1, num2));

return 1;
}

3. Register as C function

" Mymax ");

Call in 4.Lua (Test.lua)

D = Mymax (340,Notoginseng); Io.write (d)

The complete C function

#include"lua.h"#include"Lualib.h"#include"Lauxlib.h"double Max (double A, double b) {returnA>B. a:b;} static int L_max (Lua_state*L) {float NUM1= Lua_tonumber (L,1); Float num2= Lua_tonumber (L,2);    Lua_pushnumber (L, Max (NUM1, num2)); return 1;} int main () {lua_state*l =lual_newstate ();    Lual_openlibs (L);    Lua_pushcfunction (L, L_max); Lua_setglobal (L,"Mymax"); if(Lual_loadfile (L,"Test.lua") || Lua_pcall (L,0,0,0) {printf ("%s", Lua_tostring (L,-1)); }}

Lua calls C function

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.