summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorRichard Maw <richard.maw@gmail.com>2013-04-15 21:37:32 (GMT)
committer Richard Maw <richard.maw@gmail.com>2013-04-18 20:34:57 (GMT)
commitb1f1a318748eb2b0815dffc82befc06d223dea77 (patch)
tree58f6a3271c446d87089f66aa50c23b17c125d427
parentcd10f23993eac0d581c6ead9e028d83598354b7b (diff)
downloadhigher-lower-b1f1a318748eb2b0815dffc82befc06d223dea77.tar.bz2
Remove global variables
Instead of using global variables, the check_match function can use closed over values.
-rw-r--r--higher-lower.c16
1 files changed, 9 insertions, 7 deletions
diff --git a/higher-lower.c b/higher-lower.c
index 470e3b9..3309b07 100644
--- a/higher-lower.c
+++ b/higher-lower.c
@@ -8,13 +8,11 @@ static int rand_range(int min, int max){
return min + rand() / (RAND_MAX / (max - min + 1) + 1);
}
-/* Ugly global variables for state */
-static int call_count = 0;
-static int target;
-
int check_match(lua_State *L){
+ int target = lua_tointeger(L, lua_upvalueindex(1));
+ int *call_count = lua_touserdata(L, lua_upvalueindex(2));
int guess = lua_tointeger(L, 1);
- call_count += 1;
+ (*call_count) += 1;
if (guess > target) {
lua_pushinteger(L, 1);
} else if (guess < target) {
@@ -31,7 +29,8 @@ int process_strategy(char const *strategy, int min, int max){
int guess;
int exit = 0;
lua_State *L = luaL_newstate();
- target = rand_range(min, max);
+ int target = rand_range(min, max);
+ int call_count = 0;
if (luaL_loadfile(L, strategy)){
char const *errmsg = lua_tostring(L, 1);
@@ -41,7 +40,10 @@ int process_strategy(char const *strategy, int min, int max){
goto cleanup;
}
- lua_pushcfunction(L, check_match);
+ lua_pushinteger(L, target);
+ lua_pushlightuserdata(L, &call_count);
+ lua_pushcclosure(L, check_match, 2);
+
lua_pushinteger(L, min);
lua_pushinteger(L, max);