Detecting code blocks when executing a Lua script line by line - c

This may sound like a silly question but I could see no mention anywhere of this particular problem. Basically:
I want to execute a Lua script line by line, primarily to have the ability to pause/resume execution anytime and anywhere I want. What I do is simple: load a chunk with luaL_loadbuffer() and then issue a lua_pcall().
Thing is... How can I properly detect Lua blocks in order to execute them atomically?
For instance, suppose there's a function in the script -- by executing the file line by line with the method described above, I can't seem to have a way to properly recognize the function, and in consequence its contents are loaded and called one by one.
I can imagine that one solution would be to manually handle a stack where I push control keywords I can recognize in the script ("function", "if", "do", etc) and their corresponding "end" clause if I find nested blocks. Once I push the final "end" I call the entire block, but that sounds simply awful. Surely there must be a better way of doing this.
Hope it makes some sense, and thank you!

Please take a look at Lua coroutines to implement that functionality for scripting game entities. The idea is to yield the coroutine in the sleep() and waitforevent() routines you mentioned, and then resume later (e.g. after a timeout or event occurs).

Use lua_sethook().
Note that you probably do want to experiment with what exact hook call granularity you need. I'd recommend executing chunks of bytecode instructions instead. One really long line may contain many instructions.

Related

Automatic function signature and call changing and refactoring in C code base

I have found that in CLion it is possible to change functions signature, e.g. parameters' number and/or order alongside with the all places where it is called from. However it allows to do it only from a dialog window and in one-by-one manner, as far as I understood. Is there a way to write a script which will do this for all signatures and calls taken from the script or kind of input data? In other words I want to find a way to quickly refactor all code base having slightly changed something in the "task" script. I mean to modify the refactoring from time to time in one place/file and run it against all code base. Otherwise it is a lot of manual work even for one refactoring concept. But what if it is changed everyday. Here is how it is done in Clion in a one-by-one manner.
https://www.jetbrains.com/help/rider/Refactorings__Change_Signature.html

How to save state and return to a deep C function?

Background
I am porting an existing C program to work as an online game using Emscripten.
The problem is that Emscripten wants the program to be organised around a single function that is called 60 times a second. This is okay for the main game loop, except that there are quite a few places where the code displays a set of options and then waits for a key to be pressed to select the option. This is expressed as a function deep in a calling hierarchy using getch() to wait for a keypress. I find it hard to see how to fit this into the required Emscripten style of a function that runs and then completes.
Question
When the code has called a function, which has called a function, which has called a function, is there an easy way of saving the entire state of the callstack so that I can return to the same place at a later time?
What I've tried
The approach I am currently using is to set a global state variable to indicate my current location and to write all the things on the stack that seem important into static variables. I then return from all the functions. To reenter I use the global variable to decide which function to call and which variables to reload from saved data. However, this involves writing a lot of extra code and is very error-prone.
I wondered about using a thread for the game logic and just sending messages from the GUI thread, but the current thread API inside Emscripten seems to require me to try and copy all of the game data into a message so this feels like a lot more work for little benefit.
Emscripten supports setjmp/longjmp but as far as I understand, this only does half the job. I think I can use a longjmp to simply return from a deep function back to the upper level, but I don't see anyway that I can use it to later go back to where I was.
Any better ideas on how I can do this?
you cannot return from a callstack and re-enter it again. You can only make deeper calls to still be able to return to the current state. Once the function returns, the same stack (same physical memory locations) is reused for the following calls, and values get overwritten.
I don't know Emscripten; could a getch() wrapper recursively drive the loop until a key is pressed?
setjmp/longjmp saves the stack offset, but not the values on the stack. It's only useful for popping multiple frames off the stack; it's the closest C comes to a thrown exception.
You can try to use asyncify (https://github.com/kripken/emscripten/wiki/Asyncify) but it is not recommended. A quite better way would be the use of the emterpreter (https://github.com/kripken/emscripten/wiki/Emterpreter) or doppio instead (https://github.com/plasma-umass/doppio). However there might be a quite better solution in future, if you could use an evolved standard of WebAssembly. Until now the only certain ways to get such a programm running is to eliminate all recursions or to implement your own callstack. Nevertheless you will have to save your state outside of the JavaScript stack because it can not be manipulated by the programm itself. That is also the reason why longjmp does not work in this case.

How to handle labels in a scripting language I'm writing?

So I've been stewing over this for a long time, thinking about it. Here's a code example first, and then I'll explain it.
:main
dostuff
otherlabel
:otherlabel
dostuff
Alright so in this example, main is where the code starts, and it 'calls' the label 'otherlabel'. This is really just a shortcut for a jump command that changes execution to a different location in memory. My problem though is, how do I handle these labels so that they don't have to be declared before they are called?
At the moment, I'm doing a single step compilation reading straight from the source and outputting the bytecode. I am simply handling labels and adding them to a dictionary when I find them. And then I replace 'otherlabel' with a jump command to the correct location in code. But in this case that code wouldn't compile.
I've thought of a few ways to do this:
First is handling labels before anything else but this requires me to do everything in two steps and I have to deal with the same code twice, this slows down the process and just seems like a mess.
Second is queueing up the label calls until AFTER I've gone through the entire file and compiled everything else and then dealing with them, this seems much cleaner.
I'm writing this in C so I'd rather not implement complex data structures, I'm looking for the most straight forward way to handle this.
Use multiple passes. One pass isn't going to suffice for a scripting language, especially when you are getting to the more complex structures.
In a first pass, before compiling, construct your dictionary of labels.
In a later pass, when the compiling happens, just use that dictionary.
You could use "backpatching", although it sounds like that's what you've tried already; and it could be consstrued as a complex structure.
When you encounter a call to an undefined label, you emit the jump with a blank address field (probably into a buffer, otherwise this becomes the same as "multipass" if you have to re-read the file to patch it); and you also store a pointer to the blank field in a "patch-up" list in the dictionary. When you encounter the label definition, you fill-in all the blanks in the list, and proceed normally.

How to view variables during program execution

I am writing a relatively simple C program in Visual C++, and have two global variables which I would like to know the values of as the program runs. The values don't change once they are assigned, but my programming ability is not enough to be able to quickly construct a text box that displays the values (I'm working in Win32) so am looking for a quick routine that can perhaps export the values to a text file so I can look at them and check they are what they ought to be. Values are 'double'.
I was under the impression that this was the purpose of the debugger, but for me the debugger doesn't run as the 'file not found' is always the case.
Any ideas how I can easily check the value of a global variable (double) in a Win32 app?
Get the debugger working. You should maybe post another question with information about why it won't work - with as much info as possible.
Once you have done that, set a breakpoint, and under Visual C++ (I just tried with 2010), hover over the variable name.
You could also use the watch window to enter expressions and track their values.
If your debugger isn't working try using printf statements wherever the program iterates.
Sometimes this can be a useful way of watching a variable without having to step into it.
If however you wish to run through the program in debug mode set a breakpoint as suggested (in VS2010 you can right click on the line you want to set a breakpoint on).
Then you just need to go to Toolbars -> Debug Toolbar.
I usually like to put #ifdef _DEBUG (or write an appropriate macro or even extra code) to do the printing, and send to the output everything that can help me tracking what the program's doing. Since your variables are never changing, I would do so.
However, flooding the console with lots of values is bad imo, and in such cases I would rely on assertions and the debugger - you should really see why it's not working.
I've done enough Python and Ruby to tell you that debugging a complex program when all you have is a printf, although doable, is extremely frustrating and takes way longer than what it should.
Finally, since you mention your data type is double (please make sure you have a good reason for not using floats instead), in case you add some assertion, remember that == is to be avoided unless you know 100% that == is what you really really want (which is unlikely if your data comes from calculations).

Advanced Memory Editing/Function Calling

I've gotten extremely interested into coding trainers (Program that modifies value of a different process) for video games. I've done the simple 'god-mode' and 'unlimited money' things, but I want to do alot more than that. (Simple editing using WriteProcessMemory)
There are memory addresses of functions on the internet of the video game I'm working on, and one of functions is like "CreateCar" and I'm wanting to call that function from an external program.
My question: How can I call a function from an external process in C/C++, provided the function address, using a process handle or other method.
PS: If anyone could link me to tools (I've got debuggers, no need for more..) that help with this sort of thing, that'd be nice.
You can't, at least not safely. If the function has exactly one parameter, you can create a new thread in that process at the function address. If it has more, you might want to inject a DLL to do it.
But neither of these solutions are safe because creating a new thread to run the function can and will corrupt data structures if other threads are currently using them. The only safe way to call a function in another process is to somehow insert the call in exactly the right place in that process so that it's logically correct for that program. Never mind the technical hurdles (inserting hooks at arbitrary locations); you need to know exactly how the program works, which basically means you have a lot of reverse engineering ahead of you (or you need to get the source code).

Resources