Quick Master Lua 5.3--Extensions for your program (2)

Source: Internet
Author: User

Q: How do I call Lua's functions in C?

A:
1, the function name into the stack.
2, the parameters in accordance with the order of formal parameter into the stack.
3, call the function. This procedure takes the parameters of the function out of the stack, and the return value of the function is put into the stack after the call completes.
4. Gets the return value of the function.
In the "Config.lua" file:

function f(x, y)    return2math.sin(y)) / (1 - x)end

In the "main.c" file:

#include <stdarg.h>#include <stdio.h>#include <stdlib.h>#include <lua.h>#include <lauxlib.h>#include <lualib.h>voidError (Lua_state *l,Const Char*FMT, ...)    {va_list ARGP; Va_start (ARGP, FMT);vfprintf(stderr, FMT, ARGP);    Va_end (ARGP); Lua_close (L);Exit(exit_failure);}voidLoad (lua_state *l,Char*filename) {if(Lual_loadfile (l, filename) | | Lua_pcall (L,0,0,0)) Error (L,"Cannot run configuration file:%s", Lua_tostring (L,-1));}//function calls Lua's same-name function internally. DoubleF (lua_state *l,DoubleXDoubleY) {Doublez =0.0; Lua_getglobal (L,"F");//Put the function name into the stack.     //parameters are entered into the stack sequentially in the order of the function's parameter in Lua. Lua_pushnumber (L, x); Lua_pushnumber (L, y);if(Lua_pcall (L,2,1,0) !=0)//In protected mode call function, 2 parameters, 1 return values. Error (L,"Error running function ' F ':%s", Lua_tostring (L,-1));if(!lua_isnumber (L,-1))//Gets the return value of the function. Error (L,"function ' F ' must return a number"); z = Lua_tonumber (L,-1); Lua_pop (L,1);//Popup return value to ensure that the state of the stack is the same as when the function was called.     returnZ;}intMainvoid) {Lua_state *l = Lual_newstate ();    Lual_openlibs (L); Load (L,"Config.lua");printf("%f\n", F (L,0.5,0.5)); Lua_close (L);return 0;}
prompt> gcc main.-llua-ldl-lm-Wallprompt>./a.out0.239713
Q: How do I implement a function overload similar to C + + in the form of a LUA function called C?

A: We continue to expand the program in the example above (in this case it is similar to the method of JNI invocation),
In the "main.c" file:

#include <stdarg.h>#include <stdio.h>#include <stdlib.h>#include <string.h>#include <stdarg.h>#include <lua.h>#include <lauxlib.h>#include <lualib.h>voidError (Lua_state *l,Const Char*FMT, ...)    {va_list ARGP; Va_start (ARGP, FMT);vfprintf(stderr, FMT, ARGP);    Va_end (ARGP); Lua_close (L);//Turn off the LUA state machine.     Exit(exit_failure);//To exit with a failure. }voidLoad (lua_state *l,Char*filename) {if(Lual_loadfile (l, filename) | | Lua_pcall (L,0,0,0)) Error (L,"Cannot run configuration file:%s", Lua_tostring (L,-1));}/* "func": the name of the called Lua function.   * "SIG": Parameter and return worthwhile type.   ' d ': Double.   ' I ': integer.   ' s ': string. ' > ': The delimiter between the parameter and the return value. If the function does not return a value, it can be ignored. * "...": Parameters and return value variables. */voidCall_va (Lua_state *l,Const Char*func,Const Char*sig, ...) {va_list VL;intNarg =0, nres =0;the number of parameters and the number of return values. Va_start (VL, SIG); Lua_getglobal (L, func);//Put LUA functions into the stack. Narg =0; while(*sig)//Determine the type of the parameter individually and enter the stack in the appropriate way. {Switch(*sig++) { Case ' d ':/ * Double argument * /Lua_pushnumber (L, Va_arg (VL,Double)); Break; Case ' I ':/ * int argument * /Lua_pushinteger (L, Va_arg (VL,int)); Break; Case ' s ':/ * String argument * /Lua_pushstring (L, Va_arg (VL,Char*)); Break; Case ' > '://Parameters have been obtained, jump out of "while".                 GotoEndwhile;default: Error (L,"Invalid option (%c)", * (SIG-1)); } narg++;/ * Add 1 to the stack size.         If execution fails (there is not enough memory space), an error is made.         * The last parameter is the extra information shown in the error message ("NULL" stands for no additional information).         * Because this function receives variable parameters, that is, you can receive any number of parameters, you must check the size of the stack space. */Lual_checkstack (L,1,"Too many arguments"); }endwhile:nres =strlen(SIG);//Gets the number of return values.     if(Lua_pcall (L, Narg, Nres,0) !=0) Error (L,"Error running function '%s ':%s", Func, Lua_tostring (L,-1)); Nres =-nres;the number of//return values is reversed and can be obtained from the first return value by a negative index.      while(*sig)//Gets the return value. {Switch(*sig++) { Case ' d ':/ * Double result * /                if(!lua_isnumber (L, nres)) error (L,"wrong result type"); *va_arg (VL,Double*) = Lua_tonumber (L, nres); Break; Case ' I ':/ * int result * /                if(!lua_isinteger (L, nres)) error (L,"wrong result type"); *va_arg (VL,int*) =(int) Lua_tointeger (L, nres); Break; Case ' s ':/ * String result * /                if(!lua_isstring (L, nres)) error (L,"wrong result type"); *va_arg (VL,Const Char* *) = lua_tostring (L, nres); Break;default: Error (L,"Invalid option (%c)", * (SIG-1));    } nres++; } va_end (VL);}intMainvoid){Doublez =0.0f;    Lua_state *l = Lual_newstate ();    Lual_openlibs (L); Load (L,"Config.lua");//Call Lua's "F" function, the first parameter is a floating-point number, the second argument is a string, and the function returns a floating-point number received by "Z". Call_va (L,"F","Ds>d",2.W,"0.5", &z);printf("%f\n", z); Lua_close (L);return 0;}
prompt> gcc main.-llua-ldl-lm-Wallprompt>./a.out0.239713
Additional:

1 call_va() . It is not necessary to determine whether the specified "func" is a valid function in Lua lua_pcall() and can catch this error.
2. Because the return value of the LUA function may be a string, call_va() the return value cannot be stacked. This job requires the caller to dump the return value and then manually stack the result.

Quick Master Lua 5.3--Extensions for your program (2)

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.