How to share data between two Lua scripts - c++

I'm not even sure if my plan for doing things is the best way, so I apologize if this post is a bit vague. Also, I understand that similar questions have been asked before. However, I haven't been able to find anything that pertained to my situation and that made sense to me.
So me and my friends from school are building arcade machine, and I'm planning on putting together the main GUI that allows the user to select different games and load them if they have enough tokens. However, these separate windows will have to share some variables, mainly the number of tokens in the machine. I figured a separate Lua program could store such variable, and also have requests sent to it to perform other functions like opening and closing the different windows. Also, in case it's important to note, we will be using the Love2D engine for the games and be running all this on a Linux machine.
By what I've read, there seems to be some C and C++ code involved in this. I know next to nothing about C or C++, and we're trying to get this project moving along, so if you could include some code in your answer and instruct me on how to use it, that'd would be amazing. I can come back later and learn some C or C++, but right now Lua is my top priority.
My questions:
Is there a better way to accomplish what I'm trying to do?
How should I go about doing this?
Can this be done solely with Lua, or is some C, C++, or any other external programming language/utility/etc. required?
Also, incase anyone brings it up, I have tried using global variables, but I couldn't seem to get two programs/scripts to use the same variable at once.
Again, sorry if I'm being a bit vague.
Thanks in advance!

(this method is a combination of #Puzzlem00n's suggestion and reading the comments, so I shouldn't take much credit from this at all)
Putting multiple games in one lua program!
In main.lua:
require("spaceInvaders") --require all the other Lua files
-- without the ".lua" at the end!
gamestate=spaceInvaders
function love.load()
--all the setup things
end
function love.update()
gamestate.update()
end
function love.draw()
gamestate.draw()
end
function love.keypressed(key)
gamestate.keypressed(key)
end
--and so on for the rest of the love callbacks that you need (such as love.keyreleased())
Then in each game (which is a separate Lua file such as spaceInvaders.lua):
spaceInvaders = {}
function spaceInvaders.draw()
--your draw code
end
function spaceInvaders.update()
--your update code
end
--and so on for every other callback you want to use
What this code does is it gives each game its own set of love functions. When you want to play that game, you should set gamestate to that game's name. The spaceInvaders={} line defines spaceInvaders as a table, which stores each function in place. When you define a variable as an existing variable, you are actually creating a reference to it, for example:
t = {}
table.insert(t,1) --place 1 inside t
table.insert(t,3) --also place 3 inside t
s = t
print(s[1]) --will print 1, the first value of t
t[1]=2
print(s[1]) --will print 2, as it refers to t[1], which has just been changed
Sharing variables! (I worked out this bit!)
NOW, this means you can send variables around the program with another function. If you want to share score between games, you could do the following:
in main.lua:
function love.update()
gamestate.update()
score = gamestate.returnScore() --score will always equal to the current score being returned by the game
end
in a game, such as spaceInvaders.lua:
function spaceInvaders.returnScore()
return score --or whatever the score is stored in
end
This will allow you to get a variable, such as score, from one game to main.lua!
I'm sorry if this is a little confusing but hopefully this is what you're looking for! :)

Related

Method calling using variable in object name

I'm trying to increase the ease of use of my project at work. I'm a test engineer, not a programmer. The creator won't give me any source files and said if I had ideas to forward them to him and he will code it. Well, I have a lot of time and I want to learn how my project works under the hood and also save him time. I'll start out by saying I know next to nothing about C++ and honestly don't want to learn an entire language to fix this one issue.
The base functions are load() and start(). There are multiple games on 15 racks.
For instance, if I want to load game3 on rack 2, the current "call" is game3_rack2_.load(); and game3_rack2_.start()
Basically, I want the user to select the rack and game. I'm not super concerned with the game part, but let's say the user inputs rack 6 and this 6 is stored to variable num. Is there a simple way to do game3_rack<num>_.load() and game3_rack<num>_.start() ? I could use if statements, but with the amount of games/racks and multiple calls per game/rack, it seems unfeasible. In another language we have (native to company), the above case works. The variable is evaluated before the statement is executed. I think this is known as reflection? but I'm not entirely sure.
Can I utilize a basic array?
game3[N] {game3_rack0_, game3_rack1_, game3_rack2,...game3_rackN};
then just call the user input?
num = 2; //user wants rack 2
game3[num].load(); game3[num].start(); //loads and starts game3_rack2_
Thanks in advance and apologies for my poor understanding of C++.

Printing text in different colours in the Windows CMD

I am planning to make a console game in C++, kind of like Dwarf Fortress (although I don't know if it was coded in C++), but I have encountered a big problem.
I want to display different things in different colours on the screen at once. I also need to change something that has already been printed (so that I don't have to re-print everything and make the screen flash annoyingly, especially that I will want to make changes every second or so) and I found a way to do that with WriteConsoleOutput() and although I don't know yet exactly how to use it, I'll be reading into it soon.
As for the colours, I found a post here about some ANSI Escape things, but it
a) doesn't work, even when copying the linked code from github
b) I don't know if it'll work with attempts to over-write the console in specific places with WriteConsoleOutput()
So my request is: could someone please ELI5 to me what am I supposed to do and why, as well as present with a viable solution to this combination of two problems so that I can replicate something like this, with the possibilty of changing what the characters show.
Thanks in advance!

Good coding patterns in RShiny applications?

What are some good resources/examples for good coding patterns to follow in RShiny applications?
I feel I am following two bad patterns in the shiny applications I am creating.
To make things react to user changes properly, I seem to end up wrapping most parts of server.r in observe().
At the beginning of each observe(), I want the expression to rerun if any one of a whole bunch of inputs change.
Ideally, I would like to put input[change_set] where change_set is a character vector of input names, however this gives an error of Error in [.reactivevalues: Single-bracket indexing of reactivevalues object is not allowed.
(or if I use input[[change_set]]: Error in checkName: Must use single string to index into reactivevalues)
What I end up doing to make things work is including multiple lines of input$var1, input$var2, ..., input$var15. This feels very wrong.
I am not making use of any functions like: reactive(), reactiveValues(), isolate(), withReactiveDomain(), makeReactiveBinding(), ... . I am guessing that I probably should be, but I don't know how to use them.
The solution to this problem is likely to be me rereading the small print in the documentation and reading code from example applications. Does anybody know any good quality resources for this?

What is the best way to encrypt hardcoded strings in C++?

Warning: C++ noob
I've read multiple posts on StackOverflow about string encryption. By the way, they don't answer my doubts.
I must insert one or two hardcoded strings in my code but I would like to make it difficult to read in plain text when debugging/reverse engineering. That's not all: my strings are URLs, so a simple packet analyzer (Wireshark) can read it.
I've said difficult because I know that, when the code runs, the string is somewhere (in RAM?) decrypted as plain text and somebody can read it. So, assuming that is not possible to completely secure my string, what is the best way of encrypting/decrypting it in C++?
I was thinking of something like this:
//I've omitted all the #include and main stuff of course...
string encryptedUrl = "Ajdu67gGHhbh34590Hb6vfu6gu" //Encrypted url with some known algorithm
URLDownloadToFile(NULL, encryptedUrl.decrypt(), C:\temp.txt, 0, NULL);
What about packet analyzing? I'm sure there's no way to hide the URL but maybe I'm missing something? Thank you and sorry for my worst english!
Edit 1: What my application does?
It's a simple login script. My application downloads a text file from an URL. This file contains an encrypted string that is read using fstream library. The string is then decrypted and used to login on another site. It is very weak, because there's no database, no salt, no hashing. My achievement is to ensure that neither the url nor the login string are "easy" to read from a static analisys of the binary, and possibly as hard as possible with a dynamic analysis (debugging, revers engineering, etc).
If you want to stymie packet inspectors, the bare minimum requirement is to use https with a hard-coded server certificate baked into your app.
There is no panacea for encrypting in-app content. A determined hacker with the right skills will get at the plain url, no matter what you do. The best you can hope for is to make it difficult enough that most people will just give up. The way to achieve this is to implement multiple diverse obfuscation and tripwire techniques. Including, but not limited to:
Store parts of the encrypted url and the password (preferably a one-time key) in different locations and bring them together in code.
Hide the encrypted parts in large strings of randomness that looks indistinguishable from the parts.
Bring the parts together piecemeal. E.g., Concatenate the first and second third of the encrypted url into a single buffer from one initialisation function, concatenate this buffer with the last third in a different unrelated init function, and use the final concatenation in yet another function, all called from different random places in your code.
Detect when the app is running under a debugger and have different functions trash the encrypted contents at different times.
Detection should be done at various call sites using different techniques, not by calling a single "DetectDebug" function or testing a global bool, both of which create a single point of attack.
Don't use obvious names, like, "DecryptUrl" for the relevant functions.
Harvest parts of the key from seemingly unrelated, but consistent sources. E.g., read the clock and only use a few of the high bits (high enough that that they won't change for the foreseeable future, but low enough that they're not all zero), or use a random sampling of non-volatile results from initialisation code.
This is just the tip of the iceberg and will only throw novices off the scent. None of it is going to stop, or even significantly slow down, a skillful attacker, who will simply intercept calls to the SSL library using a stealth debugger. You therefore have to ask yourself:
How much is it worth to me to protect this url, and from what kind of attacker?
Can I somehow change the system design so that I don't need to secure the url?
Try XorSTR [1, 2]. It's what I used to use when trying to hamper static analysis. Most results will come from game cheat forums, there is an html generator too.
However as others have mentioned, getting the strings is still easy for anyone who puts a breakpoint on URLDownloadToFile. However, you will have made their life a bit harder if they are trying to do static analysis.
I am not sure what your URL's do, and what your goal is in all this, but XorStr + anti-debug + packing the binary will stop most amateurs from reverse engineering your application.

Interesting Console Program for C++ beginners

I’m teaching an entry-level C++ programming class. We only use iostream in the class (No GUI). It seems like students are not so excited to printout strings and numbers to their console. (Most students even never used the console before.) It is hard to motivate or convey the excitement of programming by showing strings in their console.
What would be a good and exciting console program that can be written by C++ beginners? I’m looking for something doable with basic C++ skill + a bit challenging + very exciting, which can motivate students to learn programming languages.
Any comments will be appreciated.
When I taught an undergrad intro course, we did the Game of Fifteen in straight C as the third homework project. It's pretty well scoped, and it's a game, so there's some inherent motivation there.
Back when I taught, I made an early project be an ATM machine.
Text-only interface, with basic operations like withdraw, deposit, query balance, transfer between accounts, etc.
It was something that everyone was already familiar with, it didn't take huge amounts of programming time, but it did help students feel like it was a practical and realistic program.
Other similar ideas would be a cash-register (handle refunds, coupons, items priced by the pound, sales-tax, store specials, etc, etc), or a cell-phone billing program (separate daytime, night, and weekend minutes, bill text messages, picture messages separately, etc).
How about a system that generates a set of poker hands from a deck? While clearly defined, the intricacies of ensuring no duplicate cards etc, make it a good entry level challenge.
As an extension, you could have the system take an input as to whether you want to bet or fold, and effectively play a poker game.
Finally, a good design would allow them to switch the console for a gui front-end later on (e.g. intermediate class).
I always enjoyed problems where there's a real world purpose for doing it. Something like calculating a mathematical equation, or a range of prime numbers. A lot of stuff on ProjectEuler would be good, I would think. Not everybody likes math (but then again, it's kind of a necessary thing for computer science!).
Instead of just printing to the screen you could make ascii animations.
Introduce your students to pipes and filters. Create a useful utility that takes data from stdin and directs its output to stdout. Create another utility that does something else using that same protocol. Create a third utility. Demonstrate how robustly the utilities can work together.
For example, create a clone of the GNU head and tee utilities, and perhaps add a new utility called cap which capitalizes letters. Then demonstrate how you can get the first 3 lines of a text file capitalized and tee'd to a file and stdout. Next, demonstrate how you use the same utilities, without changing a single line of code, to take the first 5 lines of a file and output to the screen the capitalized letters and to a file the original letters.
When I took C++ we had to replicate a Theseus and the Minotaur game. It lends well to outputting multiple lines to the console to form something "graphical" and it's easily based on a set of implemented rules.
I've had to program a Tower of Hanoi game in the console before, I found that quite fun. It requires use of basic data structures, user input, checking for game end conditions so it would be good for a beginner I believe.
New programming students usually find graphical programs to be the most exciting.
It doesn't have to be anything really advanced, just being able to manipulate pixels and stuff should be enough to keep them interested. Making a simple graphic class around SDL should be ok. Maybe something like this:
int main()
{
GraphicWindow graphic;
graphic.setPixel(10,20,GraphicWindow::Red);
graphic.idle();
}
Then you give out assignments like "implement a drawRect function" etc.
Perhaps a text-only version of the Lunar Lander game. You could do full ASCII art and animations (with ncurses, perhaps) as an advanced exercise, but even in a pure text form it can be interesting.
I recall playing the version that ran on the HP 67 calculator, and it was entertaining with only a seven segment display to work with.
I vaguely recall a version that probably ran on an ALTAIR 8800 written in MITS/Microsoft BASIC that used the leading part of the line to show height above ground as ASCII art, with your prompt for the next tick's burn at the right.
Another traditional choice would be to implement Hunt the Wumpus, or for the ambitious, Battleship.
One of my first programming class had a long homework about implementing a (reduced) Monopoly game.
You can use chained lists for the board.
You can use Inheritance for board tiles.
You need some logic to process players turns.
It was probably the first project I've done in CS that I could talk about to my non-tech friends and generate some interest.