From 0e6c8b389868d2f5d664d0175ad21e118f966922 Mon Sep 17 00:00:00 2001 From: "Stephen M. Cameron" Date: Thu, 12 Aug 2021 08:24:15 -0400 Subject: [PATCH] Factor out commodity lookup code Signed-off-by: Stephen M. Cameron --- commodities.c | 10 ++++++++++ commodities.h | 2 ++ snis_server.c | 12 +++++------- 3 files changed, 17 insertions(+), 7 deletions(-) diff --git a/commodities.c b/commodities.c index 3d0e35da..05d4cb6c 100644 --- a/commodities.c +++ b/commodities.c @@ -376,6 +376,16 @@ int add_commodity(struct commodity **c, int *ncommodities, const char *category, return n - 1; } +int lookup_commodity(struct commodity *c, int ncommodities, const char *commodity_name) +{ + int i; + + for (i = 0; i < ncommodities; i++) + if (strcasecmp(commodity_name, c[i].name) == 0) + return i; + return -1; +} + const char *commodity_category(int cat) { if (cat < 0 || cat >= ncategories) diff --git a/commodities.h b/commodities.h index 9eb7b529..24c85cd7 100644 --- a/commodities.h +++ b/commodities.h @@ -50,6 +50,8 @@ float commodity_calculate_price(struct commodity *c, int add_commodity(struct commodity **c, int *ncommodities, const char *category, const char *name, const char *unit, const char *scans_as, float base_price, float volatility, float legality, int odds); +int lookup_commodity(struct commodity *c, int ncommodities, const char *commodity_name); + const char *commodity_category(int cat); const char *commodity_category_description(int cat); const int ncommodity_categories(void); diff --git a/snis_server.c b/snis_server.c index 6b4efb9f..89949d60 100644 --- a/snis_server.c +++ b/snis_server.c @@ -21403,13 +21403,11 @@ static int l_lookup_commodity(lua_State *l) const char *lua_commodity_name = luaL_checkstring(l, 1); int i; - for (i = 0; i < ncommodities; i++) { - if (strcasecmp(lua_commodity_name, commodity[i].name) == 0) { - lua_pushnumber(l, (float) i); - return 1; - } - } - lua_pushnil(l); + i = lookup_commodity(commodity, ncommodities, lua_commodity_name); + if (i < 0) + lua_pushnil(l); + else + lua_pushnumber(l, (float) i); return 1; }