Bug in validation code, Conditions always true - c++

I seem to have an issue with my CheckBet() method for a Slot Machine I'm making.
Basically, I check the users bet before I spin the Machines wheels.
For some reason CheckBet() is returning true. I'm unsure what I'm doing incorrectly.
The Problem is, the "SETUP CODE" will ALWAYS run.
SETUP CODE
validbet = CheckBet(Player_Bet, Player_Chips);
if(validbet);
{
Player_Chips = DeductChips(Player_Bet, Player_Chips);
RedrawStatistics(Player_Chips, Winning_Chips, Player_Bet);
//Winning_Chips = CheckResult(SpinChamber(40, 11, 2), SpinChamber(39, 11, 1), SpinChamber(38, 11, 0), Player_Bet);
}
CHECKBET
inline bool CheckBet(int Player_Bet, int Player_Chips)
{
bool validbet = true;
if (Player_Bet <= 0)
{
Draw_String(26, 17, "You Must Bet at least 20 Chips");
validbet = false;
}
else if (Player_Bet > Player_Chips)
{
Draw_String(26, 17, "You don't own that many chips!");
validbet = false;
}
return validbet;
}

This is the problem:
if(validbet);
Your if statement isn't doing anything!
Then this block of code gets executed always - it's not related to the if:
{
Player_Chips = DeductChips(Player_Bet, Player_Chips);
RedrawStatistics(Player_Chips, Winning_Chips, Player_Bet);
//Winning_Chips = CheckResult(SpinChamber(40, 11, 2), SpinChamber(39, 11, 1), SpinChamber(38, 11, 0), Player_Bet);
}
remove the ; after the if statement so that the block is the statement that the if applies to:
if(validbet)
{
Player_Chips = DeductChips(Player_Bet, Player_Chips);
RedrawStatistics(Player_Chips, Winning_Chips, Player_Bet);
//Winning_Chips = CheckResult(SpinChamber(40, 11, 2), SpinChamber(39, 11, 1), SpinChamber(38, 11, 0), Player_Bet);
}

Related

How can I read and write to nested lua tables from C++?

I have a nested table in my lua code that I want to pass to C++ so the native code can manipulate it:
-- Some persistent data in my game
local data = {
{ 44, 34, 0, 7, },
{ 4, 4, 1, 3, },
}
-- Pass it into a C++ function that can modify the input data.
TimelineEditor(data)
How do I write my C++ code to read the nested table and modify its values?
Reading Lua nested tables in C++ and lua c read nested tables both describe how I can read from nested tables, but not how to write to them.
Short answer
Lua uses a stack to get values in and out of tables. To modify table values you'll need to push the table you want to modify with lua_rawgeti, push a value you want to insert with lua_pushinteger, and then set the value in the table with lua_rawseti.
When writing this, it's important to visualize the stack to ensure you use the right indexes:
lua_rawgeti()
stack:
table
lua_rawgeti()
stack:
number <-- top of the stack
table
lua_tonumber()
stack:
number
table
lua_pop()
stack:
table
lua_pushinteger()
stack:
number
table
lua_rawseti()
stack:
table
Negative indexes are stack positions and positive indexes are argument positions. So we'll often pass -1 to access the table at the stack. When calling lua_rawseti to write to the table, we'll pass -2 since the table is under the value we're writing.
Example
I'll add inspect.lua to the lua code to print out the table values so we can see that the values are modified.
local inspect = require "inspect"
local data = {
{ 44, 34, 0, 7, },
{ 4, 4, 1, 3, },
}
print("BEFORE =", inspect(data, { depth = 5, }))
TimelineEditor(data)
print("AFTER =", inspect(data, { depth = 5, }))
Assuming you've figured out BindingCodeToLua, you can implement the function like so:
// Replace LOG with whatever you use for logging or use this:
#define LOG(...) printf(__VA_ARGS__); printf("\n")
// I bound with Lunar. I don't think it makes a difference for this example.
int TimelineEditor(lua_State* L)
{
LOG("Read the values and print them out to show that it's working.");
{
int entries_table_idx = 1;
luaL_checktype(L, entries_table_idx, LUA_TTABLE);
int n_entries = static_cast<int>(lua_rawlen(L, entries_table_idx));
LOG("%d entries", n_entries);
for (int i = 1; i <= n_entries; ++i)
{
// Push inner table onto stack.
lua_rawgeti(L, entries_table_idx, i);
int item_table_idx = 1;
luaL_checktype(L, -1, LUA_TTABLE);
int n_items = static_cast<int>(lua_rawlen(L, -1));
LOG("%d items", n_items);
for (int i = 1; i <= n_items; ++i)
{
// Push value from table onto stack.
lua_rawgeti(L, -1, i);
int is_number = 0;
// Read value
int x = static_cast<int>(lua_tonumberx(L, -1, &is_number));
if (!is_number)
{
// fire an error
luaL_checktype(L, -1, LUA_TNUMBER);
}
LOG("Got: %d", x);
// pop value off stack
lua_pop(L, 1);
}
// pop table off stack
lua_pop(L, 1);
}
}
LOG("Overwrite the values");
{
int entries_table_idx = 1;
luaL_checktype(L, entries_table_idx, LUA_TTABLE);
int n_entries = static_cast<int>(lua_rawlen(L, entries_table_idx));
LOG("%d entries", n_entries);
for (int i = 1; i <= n_entries; ++i)
{
// Push inner table onto stack.
lua_rawgeti(L, entries_table_idx, i);
int item_table_idx = 1;
luaL_checktype(L, -1, LUA_TTABLE);
int n_items = static_cast<int>(lua_rawlen(L, -1));
LOG("%d items", n_items);
for (int j = 1; j <= n_items; ++j)
{
int x = j + 10;
// Push new value onto stack.
lua_pushinteger(L, x);
// rawseti pops the value off. Need to go -2 to get to the
// table because the value is on top.
lua_rawseti(L, -2, j);
LOG("Wrote: %d", x);
}
// pop table off stack
lua_pop(L, 1);
}
}
// No return values
return 0;
}
Output:
BEFORE = { { 44, 34, 0, 7 }, { 4, 4, 1, 3 } }
Read the values and print them out to show that it's working.
2 entries
4 items
Got: 44
Got: 34
Got: 0
Got: 7
4 items
Got: 4
Got: 4
Got: 1
Got: 3
Overwrite the values
2 entries
4 items
Wrote: 11
Wrote: 12
Wrote: 13
Wrote: 14
4 items
Wrote: 11
Wrote: 12
Wrote: 13
Wrote: 14
AFTER = { { 11, 12, 13, 14 }, { 11, 12, 13, 14 } }

Is it faster to use a bool and return later or call function and return immediately? C++

I have a question, which method would be theoretically faster to run? I have an extremely CPU intensive function, which doesn't run under certain conditions. Basically what I'm asking is, is it faster to just copy the calling code that uses many arguments many times in the same function, or is it faster to just use a bool to make the assembly smaller? Thanks
bool ShouldNotDoExpensiveFunction = false;
if (!somefunction())
{
ShouldNotDoExpensiveFunction = true;
}
else if (!somefunction2())
{
ShouldNotDoExpensiveFunction = true;
}
else if (!somefunction3())
{
ShouldNotDoExpensiveFunction = true;
}
else if (!somefunction4())
{
ShouldNotDoExpensiveFunction = true;
}
if (!ShouldNotDoExpensiveFunction)
{
return RunExpensiveFunction(1, 2, 3, 4, 5, 6, 7, 8, 9);
}
else
{
return RunInexpensiveFunction(1, 2);
}
or
if (!somefunction())
{
return RunInexpensiveFunction(1, 2);
}
else if (!somefunction2())
{
return RunInexpensiveFunction(1, 2);
}
else if (!somefunction3())
{
return RunInexpensiveFunction(1, 2);
}
else if (!somefunction4())
{
return RunInexpensiveFunction(1, 2);
}
else
{
return RunExpensiveFunction(1, 2, 3, 4, 5, 6, 7, 8, 9);
}
Both snippets are likely to have comparable performance. Since your function is very CPU intensive, the potential marginal difference between these approaches is very likely to be insignificant. A compiler might even generate identical assembly for each.
The former is superior to the latter not because of performance reasons, but because you avoid repeating the arguments thereby making the code less fragile to change.
There is an even better approach that doesn't require any repetition:
return somefunction() && somefunction2() && somefunction3() && somefunction4()
? RunExpensiveFunction(1, 2, 3, 4, 5, 6, 7, 8, 9)
: RunInexpensiveFunction(1, 2);

Finding Prime Numbers with Javascript

I am trying to write a script which displays the prime numbers from 0 to 100, but when I execute it, the browser crashes. JSHint didn't detect any error.
I'd like to learn why this code doesn't work: I am not interested in finding a totally different code( like this one) that completes the same task.
This is the first code I've ever written, so I apologise in advance for all the silly mistakes I overlooked.
var i;
var m;
var primeArr = [2, 3, 5, 7, 11, 13, 17, 19];
var theMaxNumber = 100;
var theMinNumber = 21;
var theCounter = -1;
function myFunction() {
for (i = theMinNumber; i < theMaxNumber; i += 2) {
for (m = 0; m < primeArr.length; m++) {
if (i % primeArr[m] !== 0) {
theCounter++;
if (theCounter === primeArr.length) {
primeArr.push(i);
}
if (m === primeArr.length) {
theCounter = -1;
}
}
}
}
console.log( primeArr.toString());
}
This is how it should work in theory:
1) the function finds out whether or not the number i is divisible for a prime number smaller then itself.
2) In case it is, theCounter is resetted and i is incremented by two.
3) In case it isn't, theCounter is incremented by one. If, at the end of the cycle, i is not divisibile for all the prime numbers smaller than itself, it means that it's a prime number: i is pushed in the array (because theCounter = == primeArr.length), then i is incremented by two.
edit: I fixed all the errors in the code, it works perfectly now:
var i;
var m;
var primeArr = [3, 5, 7, 11, 13, 17, 19];
var theMaxNumber = 100;
var theMinNumber = 21;
var theCounter = 0;
function myFunction() {
for (i = theMinNumber; i < theMaxNumber; i += 2) {
theCounter = 0;
for (m = 0; m < primeArr.length; m++) {
if (i % primeArr[m] !== 0) {
theCounter++;
}
if (theCounter === primeArr.length) {
primeArr.push(i);
}
}
}
primeArr.unshift(2);
console.log( primeArr.toString());
}
Your stop condition is wrong in the inner for loop it has an infinite loop increasing primeArr for ever until it crashes the JS engine.
Add an "alert" or "debugger" command to see the issue
for (m = 0; m < primeArr.length; m++) {
if (i % primeArr[m] !== 0) {
theCounter++;
if (theCounter === primeArr.length) {
primeArr.push(i);
}

C++ scope of variables inside try

Consider this code:
try {
const Asdf &a = map1.at(index1);
const Bsdf &b = map2.at(index2);
} catch(std::out_of_range&) {
return false;
}
// <code>
std::cout<<a[b[42]]; // May throw std::out_of_range which should not be caught here.
return true;
<code> uses a and b. I have two options:
Put <code> in the try block
Take pointers in the try block, dereference them afterwards
The first option is wrong because if <code> throws std::out_of_range the function will return false, which should only happen if the map lookup fails.
The second option can be a bit ugly:
const Asdf *a;
const Bsdf *b;
try {
a = &map1.at(index1); // What?
b = &map2.at(index2);
} catch(std::out_of_range&) {
return false;
}
std::cout << (*a)[(*b)[42]];
return true;
Is there a better way? Something like try-except-else in Python would be nice, but that doesn't exist in C++.
It's not necessary to do any exception handling. std::map::find, given a key, will give you an iterator. If the element doesn't exist within the map, then find will return the end iterator (i.e. map.end()).
When de-referencing the iterator, you will receive a pair of values. The first being the key and the second being the object.
auto aIt = map1.find(index1);
auto bIt = map2.find(index2);
if(aIt == map1.end() || bIt == map2.end())
{
return false;
}
const Asdf &a = aIt->second;
const Bsdf &b = bIt->second;
std::cout << a[b[42]];
return true;
Note that iterators in C++ are defined such that the begin iterator is at the start and the end iterator is past the last element (http://en.cppreference.com/w/cpp/iterator/end), i.e. the range for iterators within a container is: [begin, end).
Solution 1:
Why include the code in the try catch, embedding it in its own try catch block to make the difference between the two cases?
try {
const Asdf &a = map1.at(index1);
const Bsdf &b = map2.at(index2);
try {
// <code>
std::cout<<a[b[42]]; // May throw std::out_of_range which should not be caught here.
} catch (std::out_of_range&) {}
} catch(std::out_of_range&) {
return false;
}
return true;
But of course in this approach you can't forward to the outside of your function an out_of_range that would occur in your <code>.
Solution 2:
The other alternative is to simply check existence of the keys using map::count() without the need for exception catching:
if (map1.count(index1)==0 || map2.count(index2)==0) {
return false;
}
const Asdf &a = map1.at(index1);
const Bsdf &b = map2.at(index2);
// <code>
std::cout<<a[b[42]];
return true;
I like Miguel's solution the best, becuase it doesn't involve exception handling (when it is not called for).
But aside from that, here's another option (which I like for being short and keeping the low map operations count):
bool retval = false;
try{
const Asdf &a=map1.at(index1);
const Bsdf &b=map2.at(index2);
retval = true;
std::cout<<a[b[42]];
}catch(std::out_of_range&){
return reval;
}
// more code?
return reval;
An unconventional solution is to exploit the capturing of lambdas to extend the scope of the reference variables beyond the scope of the block. Since the objects referred by the references is valid beyond the scope block, the captured references aren't stale when used later as long as the map object remains in scope.
As an example
#include <functional>
#include <vector>
int main()
{
std::vector<std::vector< int > > map1 = { { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 },
{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 },
{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 },
{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 },
{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 } };
std::function<int()> fn;
try{
const auto &a = map1.at(1);
const auto &b = map1.at(2);
fn = [&]() {return a[b[1]]; };
}
catch (std::out_of_range&){
return false;
}
fn(); // Any exception thrown here would be caught separately from the above try catch block
}
One work around is to ensure that map actually does contain the item. It adds to overhead, but is less worse of the many worse ways I know.
try{
map1.at(index1);
map2.at(index2);
}catch(std::out_of_range&){
return false;
}
const Asdf &a=map1.at(index1);
const Bsdf &b=map2.at(index2);
Or if written in a little better way (Sorry no performance gain, only readability) unless you want to sacrifice the constness of references.
if(map1.find(index1) == map1.end() || map2.find(index2) == map2.end()) return false;
const Asdf &a=map1.at(index1);
const Bsdf &b=map2.at(index2);
You can also use std::map::const_iterator without the need of try-catch block.
std::map::const_iterator a = map1.find(index1);
if(a == map1.end()) return false;
std::map::const_iterator b = map1.find(index2);
if(b == map2.end()) return false;
Do whatever with read-only a->second and b->second.

Getting value from json-spirit

I'm using the Json-Spirit library, however i'm unsure how to read value from an object, without iterating over each of the name-value pairs.
If i have an object such that:
{
"boids":
{
"width": 10,
"count": 5,
"maxSpeedMin": 2,
"maxSpeedMax": 80,
"maxForceMin": 0.5,
"maxForceMax": 40
}
}
How can I access, for example, the width value by name?
json_spirit added support for std::map so that you can look up a value.
One of the projects in the json_spirit download is json_map_demo. This will help you to understand it better.
This is possible.
A sample code below.
string test = {
"boids":
{
"width": 10,
"count": 5,
"maxSpeedMin": 2,
"maxSpeedMax": 80,
"maxForceMin": 0.5,
"maxForceMax": 40
}
}
mValue value;
if(read(test, value))
{
mObject obj = value.get_obj();
obj = obj.find("boids")->second.get_obj();
/*Now the obj would contain the sub object,that is
{"width": 10,
"count": 5,
"maxSpeedMin": 2,
"maxSpeedMax": 80,
"maxForceMin": 0.5,
"maxForceMax": 40
}
*/
int nWidth = obj.find("width")->second.get_int();