1 // 2 // 3 4 #include "hookvars.h" 5 6 #include "scripting/scripting.h" 7 8 namespace scripting { 9 namespace api { 10 11 //**********LIBRARY: Scripting Variables 12 ADE_LIB(l_HookVar, "HookVariables", "hv", "Hook variables repository"); 13 14 ADE_INDEXER(l_HookVar, 15 "string variableName", 16 "Retrieves a hook variable value", 17 "any", 18 "The hook variable value or nil if hook variable is not defined") 19 { 20 const char* name; 21 if (!ade_get_args(L, "*s", &name)) { 22 return ADE_RETURN_NIL; 23 } 24 25 const auto scriptSystem = script_state::GetScriptState(L); 26 27 const auto& hookVars = scriptSystem->GetHookVariableReferences(); 28 const auto iter = hookVars.find(name); 29 if (iter == hookVars.end()) { 30 return ADE_RETURN_NIL; 31 } 32 if (iter->second.empty()) { 33 // Hook variable existed at some point but was removed again 34 return ADE_RETURN_NIL; 35 } 36 37 // Use the value on top of the stack 38 iter->second.back()->pushValue(L); 39 return 1; 40 } 41 42 // WMC: IMPORTANT 43 // Be very careful when modifying this library, as the Globals[] library does depend 44 // on the current number of items in the library. If you add _anything_, modify __len. 45 // Or run changes by me. 46 47 //*****LIBRARY: Scripting Variables 48 ADE_LIB_DERIV(l_HookVar_Globals, "Globals", nullptr, nullptr, l_HookVar); 49 50 ADE_INDEXER(l_HookVar_Globals, 51 "number Index", 52 "Array of current HookVariable names", 53 "string", 54 "Hookvariable name, or empty string if invalid index specified") 55 { 56 int idx; 57 if (!ade_get_args(L, "*i", &idx)) 58 return ade_set_error(L, "s", ""); 59 60 const auto scriptSystem = script_state::GetScriptState(L); 61 62 const auto& hookVars = scriptSystem->GetHookVariableReferences(); 63 64 // List 'em 65 int count = 1; 66 for (const auto& pair : hookVars) { 67 if (pair.second.empty()) { 68 // Skip empty value stacks 69 continue; 70 } 71 72 if (count == idx) { 73 return ade_set_args(L, "s", pair.first); 74 } 75 count++; 76 } 77 78 return ade_set_error(L, "s", ""); 79 } 80 81 ADE_FUNC(__len, l_HookVar_Globals, NULL, "Number of HookVariables", "number", "Number of HookVariables") 82 { 83 const auto scriptSystem = script_state::GetScriptState(L); 84 85 const auto& hookVars = scriptSystem->GetHookVariableReferences(); 86 87 // Since the values are on a stack, it is possible to have entries in the map that have no values at the moment 88 auto validHookVars = std::count_if(hookVars.cbegin(), 89 hookVars.cend(), __anon161abe1b0102(const std::pair<SCP_string, SCP_vector<luacpp::LuaReference>>& values) 90 [](const std::pair<SCP_string, SCP_vector<luacpp::LuaReference>>& values) { return !values.second.empty(); }); 91 92 return ade_set_args(L, "i", validHookVars); 93 } 94 95 } // namespace api 96 } // namespace scripting 97