Get the App
SLTechnology News&Howtos  ›  Development  › 

How to call the Cstroke function in Lua

Shulou Source: shulou.com Published: 2022-06-03 09:48:00 10月28日 Update

This article will give you a detailed explanation on how to call the C _ function in Lua. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.

1. Preface

Last time I talked about calling the function of Lua from Lua, then a friend asked how to call the function of Cmax from Cmax.

Function, so let's talk about this problem this time. First we will build a function in C++, and then

Tell Lua that there is this function, and then execute it. In addition, because the function is not defined in Lua,

We can't determine the correctness of the function, and there may be errors during the call, so we'll also talk about what went wrong with Lua.

It's a matter of management.

Call C function in 2.Lua

In lua, functions are called in the form of function pointers, and all function pointers must satisfy the following

Type:

Typedef int (* lua_CFunction) (lua_State * L)

In other words, when we define a function in C++, we must take lua_State as the parameter and int as the return value.

Called by Lua. But don't forget that our lua_State supports stacks, so you can use stacks

Pass an infinite number of parameters, the size of which is only limited by the memory size. And the int value returned only refers to the number of returned values.

The real return values are stored in the lua_State stack. What we usually do is to make a wrapper and put

All the functions that need to be called are wrap so that any function can be called.

The following example is a C++ average () function that shows how to use multiple parameters and return multiple values

Example e14.cpp

# include extern "C" {# include "lua.h" # include "lualib.h" # include "lauxlib.h"} / * the Lua interpreter * / lua_State* Lash static int average (lua_State* L) {/ * get number of arguments * / int n = lua_gettop (L); double sum = 0nint I * / for (I = 1; I

Tags: Functions parameters numbers elements functions that is methods programs articles processing detection multiple size serial numbers summation pointers numbers more correctness Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL Apple Redmi OPPO Reno Linux