Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to call the Cstroke function in Lua

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

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

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report