Character Destroy Lua C

The lua source can be found at the lua website here. We'll be using the latest version, 5.2.3 (though other recent versions of Lua will behave similarly).

  1. Character Destroy Lua Ca
  2. Character Destroy Lua Co
  3. Character Destroy Lua Characters

Once you have the latest lua source, it's time to build it. (Yes, you could just download header files and the .dll, but what's the fun in that? When available, it's always better to have the source, that way you can see how things are really working -- and you can debug more easily). Using visual studio:

  • Open up Visual Studio, and create a new project
    • Create a win 32 console application
    • In the Project Creation wizard, check the 'static library' radio button to build as a static library.
  • Add the lua source to the project. Just dragging the files directly from their folders into the project works well for this.
  • There are two source files that you don't need: lua.c and luac.c. These files contain the main program for the command line interpreter and the bytecode compiler, respectively. You can remove this files from the project if you wish. If you are building as a static library, having more than one main won't be a problem. However, if you are building as an executable, then you will need to exclude one of these files from the project. Right-click on them in the project explorer and select 'Exclude from Project'

To compile under Windows (Visual C GUI) do the following: 1: Create a new project. 2: Add the embed.c file. 3: Add the 2 Lua libraries (.lib) - Standard library and the Core library. 4: Add the locations of the Lua include files to the project options ('Directories tab'). 5: You may also have to add the locations of the library files - the. The reason might be that your script is running before the character's appearance has loaded. To do that you add repeat wait until Player.HasAppearanceLoaded. Player.HasAppearanceLoaded returns true or false. You can use the Humanoid:RemoveAccessories function. Or you can use an event called ChildAdded and check if the child is an Accessory. Lua C Table Iteration. The bug is in luanext(L, -2) line, because -2 refers to stack top minus one, which happens here to be the last argument to print. Use luanext(L, i) instead. Upd: Lua stack indexes are subject to float when moving code around at development stage, so the general advice is to. Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.

You now have a project that you can add to any solution that needs lua. Once you have added the lua project to your game, you need to do a few more steps:

  • In the properties for the project that is using lua, be sure that the directory that contains the lua .h files is included in the set of include paths. If at all possible, make these paths relative, and not absolute
  • Your project will need to get at the .lib files for the lua. There are a few ways to do this:
    • Add a reference from your project to the lua project. Right-click on your project in the project explorer, and select References:
      Add a new reference:
      Select the lua project:
    • Or, add Lua.lib to 'Additional Dependencies' (in the Librarian/Genrerl tab of the Project Property Pages) and add the directory where Lua.lib lives to 'Additional Library Directories' (also in the Librarian/Genrerl tab of the Project Property Pages).

Once we have build Lua, and set up our project dependencies correctly, we are ready to use in on our application,


First off, we need to include the proper header files. Since Lua is ANSI C, if we are coding in C++, we will need to enclose the #includes in extern 'C':

Everything that we need to mantain the current state of the interprer (all global tables, etc) is stored in a variable of type lua_State. The first thing we need to do is create an initial state (essentially, an instantiation of the lua interpreter), which is done by the call:


Every time we want to access the interpreter, we need to pass in this state variable. We can actually have as many instances of Lua state variables as we like (for instance, if we wanted to run separate instances of the interpreter on separate processors, or we wanted different scripts to have different global namespaces), though typically people just use one instance of the interpreter that all scripts use. The global tables in this state variable contain all 'core' functions, but none of the libraries. The libraries contain a bunch of important functions -- including everything in math, and i/o functions like print -- so we'd like to load them. We can load libraries with the call:


So, now we have the skeleton of a main function:

We are ready to start using lua!


We will start with the simplest way to use lua -- have the interpreter execute a file. This is functionally equivalent to the dofile command from within lua (and unsurprisingly, has the same name!). To execute the file 'test.lua', we can use the call:

Note that if we are using relative paths other than absolute paths under windows, then the system will look in the current working directory -- which is the directory that the executable file is in (if you double-click on the executable), or the directory that the project is in (if you run from within Visual Studio) You can, of course, change the working directory that the debugger uses under the project settings in Visual Studio.

So, if we use the following myFile.lua:

when the command luaL_dofile(L, 'myFile.lua') is executed, the following will be printed out

Note that the dofile command not only computes these values and prints them out, it also adds the fib function to the global namespace of our lua enviornment (stored in the C variable L).

We can also call lua functions directly from C/C++, and get back the return values to use in our C/C++ code. To call a lua function we:

  • Push the function on the top of the lua stack, using a call to
    • lua_getGlobal(lua_state *L, char *globalName)
  • Push the arguments to the function on the lua stack, using the functions:
    • lua_pushnumber(lua_state *L, float number)
    • lua_pushstring(lua_state *L, char *str)
    • lua_pushboolean(lua_state *L, bool)
    • lua_pushuserdata(lua_state *L, void *userdata)
    • lua_pushnil(lua_state *L)
  • Call the function, using the function:
    • lua_call(lua_state *L, int numArguments, int numReturnValues)
      We need to pass in both the number of arguments that we are passing in, and the number of arguments that we expect in return. Lua is very loose about the number of arguments and return value, but C/C++ is less so -- hence we need to be explicit when calling lua from C/C++.
  • Extract the return values, using the functions:
    • int lua_tointeger(lua_state *L, int stackLocation)
      Grab an integer value off the lua stack. The first return value is at index -1, the second return value is at index -2, and so on.
    • double lua_tonumber(lua_state *L, int stackLocation)
      Grab a double value off the lua stack. The first return value is at index -1, the second return value is at index -2, and so on.
    • const char *lua_tolstring(lua_state *L, int stackLocation)
      Grab a string value of the lua stack
    • int lua_toboolean(lua_state *L, int stackLocation)
      Grab a boolean value off the lua stack
      Note that these functions 'peek' at the lua stack, they don't actually remove any values from the stack. (That is done by the next function)
  • Pop the return value(s) off the top of the sack (this is just to clean up) with a call to
    • lua_pop(lua_state *L, int numReturnValsToPop);
Let's take a look at how we might call the fib function defined in the previous section to find the 13th Fibonacci number:

Let's look at a second example. Assume that we had defined the following lua function add (that we could define by calling lua_dofile):

We could call this function to add from C/C++ with the code:

So now you could write scripts that you can call from your game engine. However, these scripts won't be very useful if they can't interact with your game objects -- you need a way for your scripts to affect the game world. To do that, you need to be able to call C/C++ functions from lua. Since Lua and C++ have very different conventions for how functions are called, there is a little bit of wrapper work that needs to be done. First, write a C function that takes as input a Lua state variable (the parameters for the function will need to be extracted by hand from the lua stack -- this is slightly tedious, but not too difficult.) Then, the function will need to be registered with lua.

Step 1: Writing a C function that Lua can call

C/C++ functions that are called from lua need to take as an input parameter the lua state. The parameters can be examined on the call stack using the functions lua_tointeger, lua_tonumber, etc (described above). The first parameter is at index 1, the second parameter is at index 2, and so on. Once we have extracted the parameters, we do our calculation, and then push the result on the top of the stack.

Let's look at a slightly more complicated C function. We can write C functions that takes a variable number of parameters, and returns more than one return value. While the previous function assumed that we were passed in two parameters, we can instead query the lua state to see how many parameters were actually passed into the function. The number of parameters is stored on the top of the stack, which can be accessed by a call to lua_gettop(lua_state *L). Let's look at a function that takes in multiple parameters, and calculates the sum and average of all parameters that were passed in:

Step 2: Registering the C function for lua

Once we have written the function, we just need to register it with lua. That is, we need to add the name of the function to the global lua namespace, and provide a pointer to the function so that lua cal access it. There is a helpful macro for this: lua_register(lua_state *L, const char *name, functionPointer fn). So, to register the above two functions:

Step 3: Calling the C funcion from lua

This part is easy -- once the function is registered, lua can call it like any other function.

So, the complete round trip is:

  • Start the lua interpreter
  • Register the C functions you want lua to use
  • Call a lua function from within C, either by a call to luaL_dofile, or by calling a lua function directly
  • The lua function that you called from C can access the C function

We can also send a string straight to the lua interpreter, and it will be executed just as if that string was in a file that was executed with a dofile. So, we could do something like:

and we would get the output:

We could thus create a braindead interpreter as follows:

Note that this would not work at all in a game environment! We will look at how to embed a command-line lua interpreter within a game next time. For now, this is enough for us to play around with a bit.

Now we are ready to get our fingers dirty!

  1. Download the following project, which contains a basic skeleton lua framework
  2. Write a function in C (exposed to Lua, much like average and cAdd) that takes as input an integer n, and returns all prime numbers less than or equal to n.
    • Test your primes function in the interpreter with 'print(primes(100))'
  3. Write a function in lua nthPrime, that takes as input a number n, and returns the nth prime number. So, nthPrime(6) should return 13. We'll define nthPrime(1) to be 2, and nthPrime(0) will be undefined. Your lua function should call the c primes function
    • Small change in how lua does variable numbers of arguments: From the notes

      Alas, this does not work. But we can fix it with a simple change:

  4. Write C code that computes the 100th prime number by calling the lua nthPrime function, and prints the value out using printf. So, C calling Lua that calls C.

I am working on a game project using Corona SDK and I am running into an issue. I am trying to use string.find() in a for loop to test to determine if a value is in a certain table and if so, add that value to another table. My problem is that since string.find()/string.match does not read duplicates in this case (assuming that the for loop is the reason why). I am essentially only having '1102', '1103' instead of '1102', '1102', '1103', '1102', in the 'copy' table which is how I am trying to get this to do. Any suggestions?

Using a nested loop works.

I'm using ipairs, which is similar to for i=1, #list do.

Convolution Neural Network in torch. Error when training the network

lua,neural-network,torch

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..

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

osx,lua,osx-yosemite,libpng,torch

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..

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

function,lua,byte,equals

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 +..

Reading Lua Table from C++

c++,lua

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..

Corona : score keep running/ save it and show it after

corona,scoring

You know when to stop the score, so score = 0 local scoreTimer local scoreNumber = display.newText(score, 200, 0, nil, 50) scoreNumber.xScale = 1.2 scoreNumber.yScale = 1.2 local function updateScore() score = score + 1 scoreNumber.text = score end scoreTimer = timer.performWithDelay(100, updateScore, -1) local scoreText = display.newText('score:', 0, 0,..

Lua in-place initialized table order

c++,lua

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..

What does this warning mean in corona sdk console?

.ccscene files are produced by Corona Composer GUI. Your scene is expecting to load one of these scene files and can't find it. If you're not using the Composer GUI, you probably can ignore this.

Reading a table when function has many argument return an error

c++,arrays,lua,arguments,lua-table

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>,..

Run Lua script from Python

python,lua,lupa

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..

Write to file using Lua FFI

file,lua,ffi,luajit

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,..

Lua: how to check whether a process is running

process,lua

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

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

input,io,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..

Fast way to initialize a tensor in torch7

for-loop,matrix,lua,deep-learning,torch

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..

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

c++,c,windows,lua,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..

Lua C++ Table Iteration

c++,lua

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..

Lua search through table

lua,corona,lua-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..

Lua function selector

function,random,lua,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 - Function That Creates Detours

class,oop,pointers,lua,clone

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..

How to iterate through a table in its exact order?

loops,for-loop,lua,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..

lua - table.concat with string keys

lua,lua-table

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..

Awesome desktop manager widgets

lua,widget,awesome-wm

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,..

Call download lua script in app

c++,lua

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

Lua in pairs with same order as it's written

loops,lua,order,lua-table

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..

Character destroy lua ca

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..

Recursive loop stopping after a short time

lua,computercraft

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 ..

Nginx disable or decode url encoding when writing to access log

nginx,lua,openresty

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' ..

2D Line reflection on a “mirror”

math,lua,love2d

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..

MAMP or Mac nginx MySQL Lua

mysql,nginx,lua,osx-server

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..

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

Character Destroy Lua Ca

lua,roblox

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..

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

string,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:..

Redis Cluster: Find which master holds particular key/slot

lua,redis

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:..

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..

Erlang spawning large amounts of C processes

c,multithreading,lua,erlang,ffi

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..

Supporting “recursive objects” in lua

class,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..

Character Destroy Lua Co

Write lua_requiref in lua5.1

module,lua,load

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..

Character Destroy Lua Characters

Lua import strings from file

string,variables,lua

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

Corona sdk not view random text

text,random,lua,corona

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..

horizontal movement in game (rotated player)

math,lua,logic,love2d

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.

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

lua,neural-network,backpropagation,training-data,torch

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 =..

Computercraft Evaluate and Execute relative to ticks

lua,computercraft

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..

conditional assignment of multiple values

lua,variable-assignment

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..

Luarocks can't install a library

lua,luarocks

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 os.tempname

lua,temp

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..

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

android,gridview,lua,corona

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;..

Corona sdk random text

text,random,sdk,corona

Make sure you are localizing your variables properly. You need to declare 'mmDis' outside your function, and then do not localize it inside the function. Something like this local mmDis* -- this will ensure code from here on out all use the SAME 'mmDis' function randomText(event) display.remove(mmDis) local a =..

Trouble connecting to ESP8266 NodeMCU Server

html,http,lua,arduino,wifi

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,..

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

for-loop,lua,iterator,lua-table

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..