r/badcode •

[deleted by user]

[deleted] — view deleted post

0 Upvotes

68 comments sorted by

View all comments

2

u/Codinget Aug 29 '19
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>

int main(int argc, char** argv) {
	int tmp;
	lua_State *L=luaL_newstate(); // create a Lua state
	luaL_openlibs(L);
	
	// check whether or not we have exactly one argument
	lua_pushinteger(L, argc); //top: 1
	lua_pushinteger(L, 1); //top: 2
	lua_arith(L, LUA_OPSUB); //top: 1
	lua_pushinteger(L, 1); //top: 2
	if(lua_compare(L, 1, 2, LUA_OPLT)) {
		lua_getglobal(L, "print"); //top: 3
		lua_pushstring(L, "Too few arguments"); //top:4
		lua_call(L, 1, 0); //top: 2
		return 1;
	}
	if(!lua_compare(L, 1, 2, LUA_OPEQ)) {
		lua_getglobal(L, "print"); //top: 3
		lua_pushstring(L, "Too many arguments"); //top:4
		lua_call(L, 1, 0); //top: 2
		return 1;
	}
	lua_settop(L, 0);
	
	// read year from the command line and cast it to an int
	lua_pushstring(L, argv[1]); //top: 1
	tmp=lua_tointeger(L, -1);
	lua_pop(L, 1); //top: 0
	lua_pushinteger(L, tmp); //top: 1
	
	// clone the year so that there are 3 copies of it
	lua_settop(L, 3); //top: 3
	lua_copy(L, 1, 2);
	lua_copy(L, 1, 3);
	
	// check if the year is divisible by 4
	lua_pushinteger(L, 4); //top: 4
	lua_arith(L, LUA_OPMOD); //top: 3
	lua_pushinteger(L, 0); //top: 4
	if(lua_compare(L, 3, 4, LUA_OPEQ)) {
		lua_pop(L, 2); //top: 2
		
		// check if the year is divisible by 100
		lua_pushinteger(L, 100); //top: 3
		lua_arith(L, LUA_OPMOD); //top: 2
		lua_pushinteger(L, 0); //top: 3
		if(lua_compare(L, 2, 3, LUA_OPEQ)) {
			lua_pop(L, 2); //top: 1
			
			// check if the year is divisible by 400
			lua_pushinteger(L, 400); //top: 2
			lua_arith(L, LUA_OPMOD); //top: 1
			lua_pushinteger(L, 0); //top: 2
			if(lua_compare(L, 1, 2, LUA_OPEQ)) {
				lua_settop(L, 0); //top: 0
				lua_pushinteger(L, 1); //top: 1
			} else {
				lua_settop(L, 0); //top: 0
				lua_pushinteger(L, 0); //top: 1
			}
		} else {
			lua_settop(L, 0); //top: 0
			lua_pushinteger(L, 1); //top: 1
		}
	} else {
		lua_settop(L, 0); //top: 0
		lua_pushinteger(L, 0); //top: 1
	}
	
	// retrieve the result of the test and display it to the user
	lua_pushinteger(L, 1); //top: 2
	if(lua_compare(L, 1, 2, LUA_OPEQ)) {
		lua_getglobal(L, "print"); //top: 3
		lua_pushstring(L, "Year is a leap year"); //top: 4
		lua_call(L, 1, 0); //top: 2
	} else {
		lua_getglobal(L, "print"); //top: 3
		lua_pushstring(L, "Year is not a leap year"); //top: 4
		lua_call(L, 1, 0); //top: 2
	}
	
	// destroy the Lua state and exit
	lua_close(L);
	return 0;
}
  • Compile this with gcc leapyear.c -o detector -llua5.3 -I/usr/include/lua5.3
  • Takes exactly one command line argument which must be the year to test
  • Uses Lua and delegates the heavy computations to C code