Lua: run code while waiting for input - lua

I'm currently working on a lua program.
I want to use it in Minecraft with a mod called "OpenComputers" which allows the use of lua scripts on emulated systems.
The programm I'm working on is relatively simple: you have a console and you enter a command to control a machine.
It looks like this:
while(true) do
io.write("Enter command\n>")
cmd = io.read()
-- running code to process the command
end
But the problem is: I need a routine running in the background which checks data given by the machine.
while(true) do
-- checking and reacting
end
How can I make this work?
I can't jump to a coroutine while waiting on io.read()
It's not enough to check after someone used a command (sometimes I don't use it for days but I still have to keep an eye on it)
I'm relatively new to lua so please try to give a simple solution and - if possible - one that does not rely on third party tools.
Thank you :)

If you have some experience with opencomputers, you can add a(n asynchronous) listener for "key_down", and store the user input in a string (or whatever you want).
For example:
local userstr = ""
function keyPressed(event_name, player_uuid, ascii)
local c = string.char(ascii)
if c=='\n' then
print(userstr)
userstr = ""
else
userstr=userstr..c
end
--stores keys typed by user and prints them as a string when you press enter
end
event.register("key_down", keyPressed)

Running multiple tasks is a very broad problem solved by the operating system, not something as simple as Lua interpreter. It is solved on a level much deeper than io.read and deals with troubles numerous enough to fill a couple of books. For lua vm instead of physical computer, it may be simpler but it would still need delving deep into how the letters of code are turned into operations performed by the computer.
That mod of yours seems to already emulate os functionality for you: 1,2. I believe you'll be better off by making use of the provided functionality.

Related

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.

New to Lua, confused by error <eof>

I recently started taking an interest in Lua programming with a Minecraft addon called Computercraft, which involves console-based GUIs to control computers and other things with Lua. However, I seem to be randomly getting an error where the code requires something called an "eof". I have searched multiple manuals and how-tos, and none mention this particular error. In fact, I am having trouble finding anything with an error list. I am fairly new to programming, but have had basic Python experience. Could anyone explain what "eof" is?
An eof is do or then.
Usually eof means you have too many (or not enough) end statements. Paste code maybe?
Suppose I create a file with one too many end statements:
> edit test.lua
for i = 1, 10 do
print(i)
end
end
When I run it, and lua encounters that extra end statement on the last line where there is no code block still open, you'll get an error like:
> test.lua
bios: 337: [string "test.lua"]: 4: '<eof>' expected
(from a quick test in CCDesk pr7.1.1)
Problems with the basic structure of the blocks of lua code show up with bios on the left rather than your file name; the part of bios that loads lua files will usually tell you where it was at in the file when couldn't make sense of the code anymore (like line 4: here). Sometimes it might be a bit of a puzzle to work your way from the scene of the accident back to where things got off track. =)
Using ESPlorer there is a difference between "uploading" a script and "sending" a script. Use "Upload".
This is not the same issue as the one reported, but as searching landed me here...

How can I load a local file from embedded Rhino?

I'm using Rhino's context.evaluateString() to run some simple JavaScript from inside of Java. It's textbook right out of the Embedding Javascript guide:
String script = // simple logic
Context c = new ContextFactory().enterContext();
ScriptableObject scope = context.initStandardObjects();
Object o = context.evaluateString(scope, script, "myScript", 1, null);
ScriptableObject result = Context.jsToJava(o, ScriptableObject.class);
I'm not sure this is the current best-practice, because the main Rhino docs appear to be down, but it's working so far.
I'd like to be able to refer to a library in the working directory -- I see that Rhino shell supports load but I don't think this works in the embedding engine.
Is this possible? Is it documented anywhere? Ideally, I'd like to be able to just call something like load('other.js') and have it search directories I specify as a global property.
I have a sort-of answer that I don't really like, not least because it exposes what I'm pretty sure is a Rhino bug that drove me crazy for the last half hour:
eval("" + Packages.org.apache.commons.io.FileUtils.readFileToString(
new java.io.File("/the/local/root", "script.js");
));
{ That "" + ... is how I work around the bug -- if you eval() a Java String (such as is returned from the readFileToString call) without manually coercing it to a JavaScript native string, nothing appears to happen. The call just silently fails. }
This blindly reads an arbitrary file and evals it -- of course, this is what you do when you eval() from the Java side, so I don't worry about it too much.
Anyway, it's not elegant for a number of reasons, but it works. I'd love to hear a better answer!

hot swap code in lua

I've heard mumblings around the internets about being able to hot-swap code in Lua similar to how it's done in Java, Erlang, Lisp, etc. However, 30 minutes of googling for it has turned up nothing. Has anyone read anything substantial about this? Anyone have any experience doing it? Does it work in LuaJIT or only in the reference VM?
I'm more interested in the technique as a shortcut in development/debugging than an upgrade path in a live environment.
Lua, and most scripting languages for that matter, do not support the most generalized form of "hot swapping" as you define it. That is, you cannot guaranteeably change a file on disk and have any changes in it propagate itself into an executing program.
However, Lua, and most scripting languages for that matter, are perfectly capable of controlled forms of hot swapping. Global functions are global functions. Modules simply load global functions (if you use them that way). So if a module loads global functions, you can reload the module again if it is changed, and those global function references will change to the newly loaded functions.
However, Lua, and most scripting languages for that matter, makes no guarantees about this. All that's happening is the changing of global state data. If someone copied an old function into a local variable, they can still access it. If your module uses local state data, the new version of the module cannot access the old module's state. If a module creates some kind of object that has member functions, unless those members are fetched from globals, these objects will always refer to the old functions, not the new ones. And so forth.
Also, Lua is not thread safe; you can't just interrupt a lua_State at some point and try to load a module again. So you would have to set up some specific point in time for it to check stuff out and reload changed files.
So you can do it, but it isn't "supported" in the sense that it can just happen. You have to work for it, and you have to be careful about how you write things and what you put in local vs. global functions.
As Nicol said, the language itself doesn't do it for you.
If you want to implement something like this yourself though, it's not that hard, the only thing "preventing" you is any "leftover" references (which will still point to the old code) and the fact require caches its return value in package.loaded.
The way I'd do it is by dividing your code into 3 modules:
the reloading logic at entry point (main.lua)
any data you want to preserve across reloads (data.lua)
the actual code to reload (payload.lua), making sure you don't keep any references to that (which is sometimes not possible when you e.g. have to give callbacks to some library; see below).
-- main.lua:
local PL = require("payload")
local D = require("data")
function reload(module)
package.loaded[module]=nil -- this makes `require` forget about its cache
return require(module)
end
PL.setX(5)
PL.setY(10)
PL.printX()
PL.printY()
-- .... somehow detect you want to reload:
print "reloading"
PL = reload("payload") -- make sure you don't keep references to PL elsewhere, e.g. as a function upvalue!
PL.printX()
PL.printY()
-- data.lua:
return {} -- this is a pretty dumb module, it's literally just a table stored in `package.loaded.data` to make sure everyone gets the same instance when requiring it.
-- payload.lua:
local D = require("data")
local y = 0
return {
setX = function(nx) D.x = nx end, -- using the data module is preserved
setY = function(ny) y = ny end, -- using a local is reset upon reload
printX = function() print("x:",D.x) end,
printY = function() print("y:", y) end
}
output:
x: 5
y: 10
reloading
x: 5
y: 0
you could flesh out that logic a bit better by having a "registry module" that keeps track of all the requiring/reloading for you and abstracts away any access into modules (thus allowing you to replace the references), and, using the __index metatable on that registry you could make it pretty much transparent without having to call ugly getters all over the place. this also means you can supply "one liner" callbacks that then actually just tail-call through the registry, if any 3rd party library needs that.

Sleep Lua script without halting entire program?

I'm writing a GUI that's meant to be easily customizable by the end-users. The functions are in C++ and are called from Lua. I'm trying to make a Sleep() type function that will pause the script but not the program itself.
I was able to get it working by using threads and making one for each function. However, I want it to be an individual function. As in, instead of having it part of the CreateButton function and every other function, simply having a Delay or Sleep function that only halts the script, not the entire program.
Me being a novice at Lua, I really don't know how to go about this. Any help is appreciated.
I'd look into making a state machine using coroutines and message passing. Treat each button push like a c++ string that gets passed into coroutine resume. You can then build a little state machine that switches on the message. You can then do some UI work and then put the coroutine back to sleep till something sends it another message.
This is pretty handy if you have a state machine that does UI.
pseudo code:
c_obj:wait_for_message("mouse_down");
local message = coroutine.yield();
if(message == "mouse_down") then
update draw function.
end
c_obj:wait_for_message("mouse_up");
local message = coroutine.yield();
if(message == "mouse_up") then
Update UI..
update draw function.
end
etc...
To make your busy-waiting solution more efficient, how about using select() or similar to wait for some GUI events to process, rather than spinning? It seems like something you would need to do in the GUI regardless of the scripting side of things.

Resources