Modular code structure in Lua - lua

I've been working with Love2d recently to build a Conway's Game of Life implementation.
I really like the framework, but I haven't been able to figure out how to modularize my code, which I feel is crucial to solid code structure.
What I'm wanting to do is be able to import a file that has different functions in it and be able to access that through my main lua file. I have been able to write scripts and run entire files, but not specific functions.
Is there a way to do this in Lua? If so, how?
Thanks!

You can use the require function in LÖVE. It works similarly to how it works in Lua.
-- lib.lua
local lib = {} -- table to store the functions
function lib.inc(x)
return x + 1
end
return lib
And here is how you require it in another file (for example, main.lua) and use it:
local lib = require('lib')
function love.load()
print(lib.inc(1)) -- prints '2' in the terminal
end

Lua supports modules. Here is a tutorial on using them http://lua-users.org/wiki/ModulesTutorial

Related

How to let lua load another lua script?

I'm trying to embed Lua 5.2 into my C program.
I want to let the Lua script to be able to require and load another script. How to do it?
Suppose the Lua part has such file structure:
lua_script
- main.lua
+ utils
- custom_loader.lua
+ globals
- scene_globals.lua
- scene_levels.lua
The main.lua will try to require and import functions from custom_loader.lua, and so on...
Is it possible to do this without writing a kind-of wrapper in C?
Can the Lua script automagically just load everything it needs?
(Ps. I don't really need sandboxing for now, so it's okay for the script to do what it want.)
As decribed by the Lua require man page, it searches for the file in a path.
This path can be defined in C.
Have a look to this post : "Setting the global LUA_PATH variable from C++/C"
The require function is very pratical to load modules and libraries defined in .lua files.

Hacking Lua - Inject new functions into built Lua

I am trying to hack a game (not for cheating though) by introducing new built-in methods and functions in order to communicate with the game using sockets. Here is a small "pseudo code" example of what I want to accomplish:
Inside the Lua code I am calling my_hack() and pass the current game state:
GameState = {}
-- Game state object to be passed on
function GameState:new()
-- Data
end
local gameState = GameState:new()
-- Collect game state data and pass it to 'my_hack' ..
my_hack(gameState)
and inside my_hack the object is getting sent away:
int my_hack(lua_State * l)
{
void* gameState= lua_topointer(l, 1);
// Send the game state:
socket->send_data(gameState);
return 0;
}
Now, the big question is how to introduce my_hack() to the game?
I assume, that all built in functions must be kept in some sort of lookup table. Since all Lua code is getting interpreted, functions like import etc. will have to be statically available, right? If that is correct, then it should be "enough" to find out where this code is residing in order to smuggle my code into the game that would allow me to call my_hack() in a Lua script.
There should be two options: The first is that the Lua built is embedded inside the executable and is completely static and the second is that all Lua code gets loaded dynamically from a DLL.
This question goes out to anybody who has a slightest clue about where and how I should keep looking for the built in functions. I've tried a few things with Cheat Engine but I wasn't too successful. I was able to cheat a bit ^^ but that's not what I'm looking out for.
Sorry for not providing a full answer, but if you can provide a custom Lua VM and change the standard libraries, you should be able to to change the luaL_openlibs method in the Lua source to provide a table with my_hack() inside of it.
Since the Lua interpreter is usually statically compiled into the host executable, modifying the interpreter in some way will probably not be possible.
I think your best bet is to find some piece of Lua code which gets called by the host, and from that file use dofile to run your own code.

Embedding LuaJIT module into C application

In my application, I have all the Lua libraries exposed from the C backend. Now, I have a need to load a Lua module. The method for this seems to be :
lua_getglobal(L, "require");
lua_pushstring(L, libname);
lua_pcall(L, 1, 0, 0);
which will search the package.path to find <libname>.lua and load it.
Is it possible to build-in the Lua module into the C application (so that the module becomes part of the C application) ? so that I don't have to separately package the Lua module. Somehow I am not able to find any references or examples of this! :(
p.s. I am using LuaJIT-2.0.2, and the library in question is SciLua/Time (uses ffi)
Yes.
luajit -b Module.lua Module_bc.c
will compile a module to bytecode and output a C array initializer containing that bytecode.
If you build with shared libraries enabled and export this array from the main executable, require will find it (and will not need to look for Module.lua.)
To test that it is working, set package.path = "" before requireing the module. If it still works, you know the preload is working and it is not just using the Module.lua file from the current directory.
http://luajit.org/running.html
Other things to keep in mind:
If the module depends on an external file (using io.open), that file still needs to be present. For example some ffi modules try to open a C header file, to pass to ffi.cdef
You need to keep Module_bc.c in sync with Module.lua, e.g. with a Makefile recipe, or you will see some confusing bugs!

How to have multiple Lua files when working with Corona SDK?

I am new to developing with the Corona SDK as well as Lua.
Currently i work strictly with the main.lua file.
Is there any way in Lua (im sure there is) to break up the source code into logical, separate files?
Example:
1. Main.lua
2. Entity.lua
3. Settings.lua
Thanks!
objects.lua:
local M = {}
M.a = 3
return M
main.lua:
local objects = require('objects')
println(objects.a) --> 3
A very good discussion about this is available in the Lua users' wiki: http://lua-users.org/wiki/LuaModuleFunctionCritiqued. You should read it.
Here's a sample I wrote to demo what you're asking about: http://developer.anscamobile.com/code/object-oriented-sample-game-framework
EDIT: The forum post no longer seems to exist, so here's a link to download the sample code https://app.box.com/shared/uz5beg19h8
It divides things up into multiple files, and uses a sort of decorator pattern to add functionality like "level" or "floating character".
You don't need to only work with main.lua file. You can create separate .lua file as you need it like -
1- If you are using many scenes/views/classes for this you can create your separate .lua file for different scenes/views/classes and call these separate .lua files by using storyboard.
2- You can also create separate .lua files for creating objects which you can access in your any class.
3- There are many .lua files like appirater.lua , ui.lua, json.lua provided.

Do file only once in Lua

I was wondering if there's a way to do a lua file only once and have any subsequent attempts to do that lua file will result in a no-op.
I've already thought about doing something akin to C++ header's #if/else/endif trick. I'm wondering if there's a standard way to implement this.
James
well, require pretty much does that.
require "file" -- runs "file.lua"
require "file" -- does not run the "file" again
The only problem with require is that it works on module names, not file names. In particular, require does not handle names with paths (although it does use package.path and package.cpath to locate modules in the file system).
If you want to handle names with paths you can write a simple wrapper to dofile as follows:
do
local cache={}
local olddofile=dofile
function dofile(x)
if cache[x]==nil then
olddofile(x)
cache[x]=true
end
end
end
based on lhf's answer, but utilising package, you can also do this once:
package.preload["something"]=dofile "/path/to/your/file.lua"
and then use:
local x=require "something"
to get the preloaded package again. but that's a bit abusive...

Resources