C++ Calling Lua Functions With Same Name

  1. C++ Calling Functions Within Functions
  2. Lua Function Call
  3. C++ Calling Lua Functions With Same Name Examples

Overloading Functions in C. It is well known that C allows one to overload functions, and C does not. This is typically done by 'mangling' the name of a function, and thus including the types of its arguments in the symbol definition. Each variant of an overloaded function will then obtain a different symbolic name for the entry point. To have access the GL functions in Lua call require'luagl', or from a C host program you could call the 'luaopenluagl' function. This will create a name space called 'gl', and all the functions and constants will be inside of it. To have access the GLU functions in Lua call require'luaglu', or from a C host program you could call the 'luaopen.

I am attempting to build my first game using love2D, I have hit a problem.

The game is a bubble popping game, I want to assign a bubble to each letter on the keyboard so that when a letter is pressed, the bubble will pop.

I have an external file called 'bubble.lua' which I have tried to make an object 'bubble' with. to do that I have created a table 'bubble' in the bubble.lua which contains functions and variables. Now, this file works when called from main.lua using just one bubble, however I am going to need 26 bubbles so I thought it would be best to store each bubble in another table. For the purpose of trying this I just stored one bubble using 1 as the key.This is where I have problems.

Firstly, I know that the for loop in love.draw() does not work, and the line 'bubble[key].bubble.pop' seems to return nil as well

The for loop I can probably find the solution myself online, my main problem is the 'bubble[key].bubble.pop()' line, I cannot work out what's wrong or how to fix it.

Can anybody help me?

You may want to look at this as well:



Following the advice of the answer below I now have the following error when I press 'a':

main.lua:14: attempt to index a nil value

the updated code is below


any thoughts?

There are several issues with this code. First, you index by number when you initialize bubbles (bubbles[1]), but access them using the key as the index (bubbles[key]), which is NOT a number. You need to settle on one mechanism to index the bubbles. Let's say you picked using key as the index (instead of the number).

This loop:

should be written as:

and instead of bubbles[key].bubble.pop() you can simply do bubbles[key].pop() as bubbles[key] already returns the bubble you can pop.

To initialize, instead of bubbles[1] you need to do bubbles['a'] (or whatever other value is used by key in love.keypressed(key)).

iterating over a table passed as an argument to a function in lua


You are creating the record table before creating the bid# tables. So when you do record = {bid1, bid2, bid3} none of the bid# variables have been created yet and so they are all nil. So that line is effectively record = {nil, nil, nil} which, obviously, doesn't give the...

storyboard.removeScene(“scene name”) is not working


Hi sid here you go: _W = display.contentWidth; _H = display.contentHeight; local button = {} x = -20 for count = 1,3 do x = x + 90 y = 20 for insideCount = 1,3 do y = y + 90 button[count] = display.newImage('imgs/one.png'); button[count].x = x; button[count].y = y;...

Luarocks can't install a library


That library (and the one which it depends on) have no versioned release yet, so they are marked as DEV (which you can see in the 'Versions' section). Those libraries do not show up in searches or can't be installed by default. You need to add the 'development' repository in...

Lua in pairs with same order as it's written


In Lua, the order that pairs iterates through the keys is unspecified. However you can save the order in which items are added in an array-style table and use ipairs (which has a defined order for iterating keys in an array). To help with that you can create your own...

How to iterate through a table in its exact order?


You may utilize integer part of the table to store keys in order: function add(t, k, v, ...) if k ~= nil then t[k] = v t[#t+1] = k return add(t, ...) end return t end t = add({ }, 'A', 'hi', 'B', 'my', 'C', 'name', 'D', 'is') for i,k...

Supporting “recursive objects” in lua


Since MyClass is just a lookup in the global table (_G), you could mess with its metatable's __index to return a newly-defined MyClass object (which you would later need to fill with the details). However, while feasible, such an implementation is wildly unsafe, as you could end up with an...

Write to file using Lua FFI


I have solved this issue with the following code: local ffi = require 'ffi' ffi.cdef[[ typedef struct { char *fpos; void *base; unsigned short handle; short flags; short unget; unsigned long alloc; unsigned short buffincrement; } FILE; FILE *fopen(const char *filename, const char *mode); int fprintf(FILE *stream, const char *format,...

conditional assignment of multiple values


function foo(param_1, param_2) -- obtain the default values local p1, p2 = getBar() -- combine the provided values with default values local bar_1, bar_2 = (param_1 or p1), (param_2 or p2) -- do whatever you need with bar_1 and bar_2 end If the getBar function call is expensive and should...

lua - table.concat with string keys


Because that's what table.concat is documented as doing. Given an array where all elements are strings or numbers, returns table[i]..sep..table[i+1] ··· sep..table[j]. The default value for sep is the empty string, the default for i is 1, and the default for j is the length of the table. If i...

How I get the cdata out in c function with variable arguments using luajit?


You can't. The Lua C API and the LuaJIT FFI are deliberately separated and cannot interact. Rewrite PrintC in Lua using the FFI, or write Lua C API bindings to the library you're using p with. I.e. Use one or the other....

Multiline function tables in lua

action = { [1] = function (x) print(1) end, [2] = function (x) z = 5 end, ['nop'] = function (x) print(math.random()) end, ['my name'] = function (x) print('fred') end, } You are free to do that....

ROBLOX Lua Error in script: '=' expected near ''


Looks like a syntax error. message.Destroy() should be message:Destroy() according to this Roblox wiki page http://wiki.roblox.com/index.php?title=API:Class/Instance/Destroy Also see the section Explosions, Messages, and More at URL http://wiki.roblox.com/index.php?title=Basic_Scripting which provides similar syntax using the colon (:) operator....

Torch Lua: Why is my gradient descent not optimizing the error?


why the predictionValue variable is always the same? Why doesn't it get updates? First of all you should perform the backward propagation only if predictionValue*targetValue < 1 to make sure you back-propagate only if the pairs need to be pushed together (targetValue = 1) or pulled apart (targetValue =...

Write lua_requiref in lua5.1


Yes, you can use compat-5.3 to get many of the newer lua C API functions in lua 5.1 (and 5.2). The particular function you're looking for (luaL_requiref) you can find here...

Redis Cluster: Find which master holds particular key/slot


I still have to read the entire docs, but already found this: There are 16384 hash slots in Redis Cluster, and to compute what is the hash slot of a given key, we simply take the CRC16 of the key modulo 16384. There is a command for that op already:...

Reading a table when function has many argument return an error


The stack index -2 is the second to top element of the lua C stack. The arguments to your lua C function are also on the stack. So when you get two arguments your stack is <table>, <number> then you push a nil value and your stack is <table>, <number>,...

Lua C++ Table Iteration


The bug is in lua_next(L, -2) line, because -2 refers to stack top minus one, which happens here to be the last argument to print. Use lua_next(L, i) instead. Upd: Lua stack indexes are subject to float when moving code around at development stage, so the general advice is to...

Corona sdk not view random text


To fully understand the display.newText api of Corona SDK you can view it here: https://docs.coronalabs.com/api/library/display/newText.html For the Tap event you can view it here: https://docs.coronalabs.com/api/event/tap/index.html But I have fixed your code for you. But I really can't understand why you have 'Impact' there. but here is a working code you...

Lua error loading module 'libpng' (Torch, MacOSX)


I had a similar problem (OSX 10.9.5). You probably have multiple versions of libpng installed, with the one called during install of luarocks having architecture i386 (x86_64 required). To solve this: Try installing image again, and reading the log: luarocks install image Check the log to see if you get...

Computercraft Evaluate and Execute relative to ticks


Usually, the only things that would trigger a sort of tick, or cause a sizable amount of stoppage for a tick to pass by is pulling events (os.pullEvent,os.pullEventRaw,coroutine.yield) turtle movement does of course need a tick to go by, and do call coroutine.yield to pause the script and move. The...

horizontal movement in game (rotated player)


If you want to move sideways, you can simply add or subtract 90 degrees (in radians, that is π/2) from your r before calculating the sin/cos velocity vector.

How do I do user inputs on the same line in Lua?


When called without arguments, io.read() reads a whole line. You could read the line and get the words using pattern matching: input = io.read() opr, txt = input:match('(%S+)%s+(%S+)') The above code assumes that there is just one word for opr and one word for txt. If there might be zero...

How to Draw Circle, incrementally, to create an animated fill effect (using Corona)


This sample from caronalabs.com forums shows how you might draw an arc, which provides the discrete algorithm you would need to do what you're asking: function display.newArc(group, x,y,w,h,s,e,rot) local theArc = display.newGroup() local xc,yc,xt,yt,cos,sin = 0,0,0,0,math.cos,math.sin --w/2,h/2,0,0,math.cos,math.sin s,e = s or 0, e or 360 s,e = math.rad(s),math.rad(e) w,h =...

Lua - Is it possible to check if 2 functions are equal?


Using for functions only checks if they reference to the same function, which is not what you expected. This task is rather difficult, if not impossible at all. For really simple cases, here's an idea: function f(x) return x + 1 end local g = function(y) return y +...

Convolution Neural Network in torch. Error when training the network


C++ Calling Functions Within Functions

The problem is the convolutional neural network from this tutorial has been made to work with a fixed size input resolution of 32x32 pixels. Right after the 2 convolutional / pooling layers you obtain 64 feature maps with a 5x5 resolution. This gives an input of 64x5x5 = 1,600 elements...

Recursive loop stopping after a short time


It looks as though you are not even using the X var... so why don't you try this... this is a more effective way to keep doing the same thing over and over while true do getTarg() derp1() sleep(2.9) monInit() end ...

Trouble connecting to ESP8266 NodeMCU Server


I know nothing about NodeMCU but that is not a proper http server. For it to properly work with a browser, it should return some headers. You can try to close the connection after sending the response. Try the following: wifi.setmode(wifi.STATION) wifi.sta.config('SSID', 'password') wifi.sta.connect() srv = net.createServer(net.TCP) srv:listen(80,function(conn) conn:on('receive', function(conn,...

Awesome desktop manager widgets


You can always use NetworkManager which is available for installation in most official repos. It contains an applet which creates an icon at your system tray. You can launch the applet at start-up, placing this line in your rc.lua file: awful.util.spawn('nm-applet') or you can start it manually from your terminal,...

Lua os.tempname


The purpose of this Lua function is only to provide a unique name. There are not many options in the standard Lua library. In other words, either you use what's available in Lua, or you write your own function. However, even if you use hashes, random numbers, and so...

Nginx disable or decode url encoding when writing to access log


Short answer you can't. But, you can run an URL decode after logrotate. Here is the command : awk -v RS='x[0-9]{2}' 'RT{ORS=sprintf('%c', strtonum('0' substr(RT, 2)))} 1' ...

Lua - Function That Creates Detours


Simple detouring is easy to do with closures; no need for loadstring: function detour(cls) local detours = {} for key, value in pairs(cls) do if type(value) 'function' then -- note: ignores objects with __call metamethod detours['custom_detour_'..key] = function(...) -- Do whatever you want here return value(...) end end end...

2D Line reflection on a “mirror”


It's better to avoid working with slopes and angles if you can avoid them, because you will have to deal with annoying special cases like when the slope is +ve or -ve infinity and so on. If you can calculate the normal of the line (blue arrow), then you can...

Lua search through table


Using a nested loop works. for lk, lv in ipairs(list) do for dk, dv in ipairs(database) do if string.find(dv.serial, tostring(lv)) then table.insert(copy, dv.img) end end end I'm using ipairs, which is similar to for i=1, #list do....

How can I convert a character code to a string character in Lua?


You are looking for string.char: string.char (···) Receives zero or more integers. Returns a string with length equal to the number of arguments, in which each character has the internal numerical code equal to its corresponding argument. Note that numerical codes are not necessarily portable across platforms. For your example:...

Lua obfuscator, how to

Open a command line (e.g. under windows, that's cmd). Go into the directory where you have your local copy of XFuscator. Make sure lua is on your PATH. Type lua XFuscator.lua -h This should show the help message, which will describe the next steps....

Lua in-place initialized table order


You should push 1 and 2 on to the stack (or 0,1 if tables are 0indexed) and use lua_geti instead of iterating over the table with lua_next. Another example of how your current code is incorrect is what happens if the Lua user passes {1, 2, 3}? You would be...

Lua function selector


You don't use math.random to select a function; you use it to pick a random number, which you can then use as an index to get the function you need from a table (as one example): local list = { function() print(1) end, function() print(2) end, function() print(3) end }...

Lua import strings from file


dofile 'user.db' -- try this ...

MAMP or Mac nginx MySQL Lua


There is Jan Kneschke's lua magnet of which I maintain a fork on github. I use this in conjunction with FastCGI (and luasql.sqlite3) for a small message board, which was previously written in PHP, then python. The PHP and python versions each performed so-so (which may be due to me...

Reading Lua Table from C++


You need to call lua_next(L,-2) after lua_pushnil(L). You need lua_next because apparently you don't know the key in the table. So you have to use the table traversal protocol, which is to push the table, push nil, call lua_next(L,-2), and get the key and value on the stack. This works...

Erlang spawning large amounts of C processes


If you can make the Lua code — or more accurately, its underlying native code — cooperate with the Erlang VM, you have a few choices. Consider one of the most important functions of the Erlang VM: managing the execution of a (potentially large number of) Erlang's lightweight processes across...

Fast way to initialize a tensor in torch7


See the documentation for the Tensor:apply These functions apply a function to each element of the tensor on which the method is called (self). These methods are much faster than using a for loop in Lua. The example in the docs initializes a 2D array based on its index i...

Call download lua script in app


From C++, you could call luaL_dofile with the path to your file directly, then just call the function the usual way.


Lua: how to check whether a process is running


The following Lua library provides functions to (asynchronously) start and monitor processes. http://stevedonovan.github.io/winapi/...

Run Lua script from Python


You can use a subprocess to run your Lua script and provide the function with it's arguments. import subprocess result = subprocess.check_output(['lua', '-l', 'demo', '-e', 'test('a', 'b')']) print(result) result = subprocess.check_output(['lua', '-l', 'demo', '-e', 'test2('a')']) print(result) the -l requires the given library (your script) the -e is the code that...

A foreign function interface (FFI) is a mechanism by which a program written in one programming language can call routines or make use of services written in another.


The term comes from the specification for Common Lisp, which explicitly refers to the language features for inter-language calls as such;[1] the term is also used officially by the Haskell,[2]Rust,[3] and Python programming languages.[4] Other languages use other terminology: the Ada programming language talks about 'language bindings', while Java refers to its FFI as the JNI (Java Native Interface) or JNA (Java Native Access). Foreign function interface has become generic terminology for mechanisms which provide such services.


The primary function of a foreign function interface is to mate the semantics and calling conventions of one programming language (the host language, or the language which defines the FFI), with the semantics and conventions of another (the guest language). This process must also take into consideration the runtime environments and/or application binary interfaces of both. This can be done in several ways:

  • Requiring that guest-language functions which are to be host-language callable be specified or implemented in a particular way, often using a compatibility library of some sort.
  • Use of a tool to automatically 'wrap' guest-language functions with appropriate glue code, which performs any necessary translation.
  • Use of wrapper libraries
  • Restricting the set of host language capabilities which can be used cross-language. For example, C++ functions called from C may not (in general) include reference parameters or throw exceptions.

FFIs may be complicated by the following considerations:

  • If one language supports garbage collection (GC) and the other does not; care must be taken that the non-GC language code does nothing to cause GC in the other to fail. In JNI, for example, C code which 'holds on to' object references that it receives from Java must 'register' this fact with the Java runtime environment (JRE); otherwise, Java may delete objects before C has finished with them. (The C code must also explicitly release its link to any such object once C has no further need of that object.)
  • Complicated or non-trivial objects or datatypes may be difficult to map from one environment to another.
  • It may not be possible for both languages to maintain references to the same instance of a mutable object, due to the mapping issue above.
  • One or both languages may be running on a virtual machine (VM); moreover, if both are, these will probably be different VMs.
  • Cross-language inheritance and other differences, such as between type systems or between object-composition models, may be especially difficult.

By language[edit]

Examples of FFIs include:

  • Ada language bindings, allowing not only to call foreign functions but also to export its functions and methods to be called from non-Ada code.[5]
  • C++ has a trivial FFI with C, as the languages share a significant common subset. The primary effect of the extern 'C' declaration in C++ is to disable C++ name mangling.
  • Clean provides a bidirectional FFI with all languages following C or the stdcall calling convention.[6][7]
  • CNI, alternative to JNI used in the GNU compiler environment.
  • D does it the same way as C++ does, with extern 'C' through extern (C++)
  • Dart includes dart:ffi[8] library to call native C code for mobile, command-line, and server applications
  • Dynamic languages, such as Python, Perl, Tcl, and Ruby, all provide easy access to native code written in C/C++ (or any other language obeying C/C++ calling conventions).
  • Factor has FFIs for C, Fortran, Objective-C, and Windows COM; all of these enable importing and calling arbitrary shared libraries dynamically.
  • The FFIs of Common Lisp and Haskell
  • Fortran 2003 has a module ISO_C_BINDING which provides interoperable data types (both intrinsic types and POD structs), interoperable pointers, interoperable global data stores, and mechanisms for calling C from Fortran and for calling Fortran from C.[9]
  • Go can call C code directly via the 'C' pseudo-package.[10]
  • GWT, in which Java is compiled to JavaScript, has an FFI called JSNI which allows Java source to call arbitrary JavaScript functions, and for JavaScript to call back into Java.
  • JNI, which provides an interface between Java and C/C++, the preferred systems languages on most systems where Java is deployed. JNA provides an interface with native libraries without having to write glue code. Another example is JNR
  • Nim has an FFI which enables it to use source from C, C++, and Objective-C. It can also interface with Javascript.
  • Julia has ccall keyword to call C (and other languages, e.g. Fortran);[11] while packages, providing similar no-boilerplate support, are available for some languages e.g. for Python[12] (to e.g. provide OO support and GC support), Java (and supports other JDK-languages, such as Scala) and R. Interactive use with C++ is also possible with Cxx.jl package.
  • PHP provides FFI to C.[13]
  • Ruby provides FFI either through the ffi gem, or through the standard library fiddle.
  • Python provides the ctypes and cffi modules. For example, the ctypes module can load C functions from shared libraries/DLLs on-the-fly and translate simple data types automatically between Python and C semantics as follows:
  • P/Invoke, which provides an interface between the Microsoft Common Language Runtime and native code.
  • Racket has a native FFI based heavily on macros that enables importing arbitrary shared libraries dynamically.[14][15]
  • Raku can call Ruby, Python, Perl, Brainfuck, Lua, C, C++, Go and Scheme Guile/Gambit[16][17]
  • Rust also defines a foreign function interface.[18]
  • Visual Basic has a declarative syntax that allows it to call non-Unicode C functions.
  • One of the bases of the Component Object Model is a common interface format, which natively uses the same types as Visual Basic for strings and arrays.
  • LuaJIT, a just-in-time implementation of Lua, has an FFI that allows 'calling external C functions and using C data structures from pure Lua code'.[19]
  • PhoneGap (was called by the name Apache Callback, but now Apache Cordova) is a platform for building native mobile applications using HTML, CSS and JavaScript. Additionally has FFIs via JavaScript callback functions for access to methods and properties of mobile phone's native features including Accelerometer, Camera (also PhotoLibrary and SavedPhotoAlbum), Compass, Storage (SQL database and localStorage), Notification, Media and Capture (playing and recording or audio and video), File, Contacts (address book), Events, Device and Connection information.[1],[2].
  • Wolfram Language provides a technology called WSTP (Wolfram Symbolic Transfer Protocol) which enables bidirectional calling of code between other languages with bindings for C++, Java, .NET and other languages.
  • Zig provides FFI to c using the builtin cImport function.[20]

In addition, many FFIs can be generated automatically: for example, SWIG. However, in the case of an extension language a semantic inversion of the relationship of guest and host can occur, when a smaller body of extension language is the guest invoking services in the larger body of host language, such as writing a small plugin [21] for GIMP.[22]

Some FFIs are restricted to free standing functions, while others also allow calls of functions embedded in an object or class (often called method calls); some even permit migration of complex datatypes and/or objects across the language boundary.

In most cases, an FFI is defined by a 'higher-level' language, so that it may employ services defined and implemented in a lower level language, typically a systems language like C or C++. This is typically done to either access OS services in the language in which the OS' API is defined, or for performance considerations.

Many FFIs also provide the means for the called language to invoke services in the host language as well.

The term foreign function interface is generally not used to describe multi-lingual runtimes such as the Microsoft Common Language Runtime, where a common 'substrate' is provided which enables any CLR-compliant language to use services defined in any other. (However, in this case the CLR does include an FFI, P/Invoke, to call outside the runtime.) In addition, many distributed computing architectures such as the Java remote method invocation (RMI), RPC, CORBA, SOAP and D-Bus permit different services to be written in different languages; such architectures are generally not considered FFIs.

Special cases[edit]

There are some special cases, in which the languages compile into the same bytecode VM, like Clojure and Java, as well as Elixir and Erlang. Since there is no interface, it is not an FFI, strictly speaking, while it offers the same functionality to the user.

Lua Function Call

See also[edit]


  1. ^'CFFI User Manual'. common-lisp.org. Retrieved 2015-06-18.
  2. ^'FFI Introduction'. HaskellWiki. Retrieved 19 June 2015. Haskell's FFI is used to call functions from other languages (basically C at this point), and for C to call Haskell functions.
  3. ^'std::ffi - Rust'. Retrieved 1 April 2021. This module provides utilities to handle data across non-Rust interfaces, like other programming languages and the underlying operating system. It is mainly of use for FFI (Foreign Function Interface) bindings and code that needs to exchange C-like strings with other languages.
  4. ^'CFFI documentation'. Retrieved 19 June 2015. C Foreign Function Interface for Python. The goal is to provide a convenient and reliable way to call compiled C code from Python using interface declarations written in C.
  5. ^'Interface to Other Languages'. Adaic.org. Retrieved 2013-09-29.
  6. ^'Foreign Export'. Retrieved 2020-05-25.
  7. ^'Calling C From Clean'. Retrieved 2018-04-25.
  8. ^'dart:ffi library'. Retrieved 2020-01-01.
  9. ^''fortran-iso-c-binding' tag wiki'. Stack Overflow.
  10. ^'cgo — The Go Programming Language'. Retrieved 2015-08-23.
  11. ^'Calling C and Fortran Code · The Julia Language'. docs.julialang.org. Retrieved 2018-02-11.
  12. ^PyCall.jl: Package to call Python functions from the Julia language, JuliaPy, 2018-02-08, retrieved 2018-02-11
  13. ^'PHP: FFI - Manual'. The PHP Group. Retrieved 13 June 2019.
  14. ^Eli Barzilay. 'The Racket Foreign Interface'. Docs.racket-lang.org. Retrieved 2013-09-29.
  15. ^'TR600.pdf'(PDF). Retrieved 2013-09-29.
  16. ^'Inline implementations'. Retrieved 2017-08-15.
  17. ^'Native Call'. Retrieved 2017-08-15.
  18. ^'Using extern Functions to Call External Code'. Retrieved 2019-06-01.
  19. ^Mike Pall. 'FFI Library'. Luajit.org. Retrieved 2013-09-29.
  20. ^'Import from C Header File'. Zig Software Foundation. Retrieved 2021-03-11.
  21. ^'4. A sample script'. Gimp.org. 2001-02-04. Retrieved 2013-09-29.
  22. ^'Script-Fu and plug-ins for The GIMP'. Gimp.org. Retrieved 2013-09-29.

External links[edit]

C++ Calling Lua Functions With Same Name Examples

Retrieved from 'https://en.wikipedia.org/w/index.php?title=Foreign_function_interface&oldid=1018893018'