From 9f88b184ac03f01771bf0f9659ec19bac57b645a Mon Sep 17 00:00:00 2001 From: Cuboid Date: Mon, 12 May 2025 15:07:54 +0100 Subject: [PATCH] Add ability to speak, and fix runtime actions so they will return new results if called with different parameters --- abilities.lua | 30 ++++++++++++++++++++++++++++++ api/execute.lua | 18 ++++++++---------- 2 files changed, 38 insertions(+), 10 deletions(-) diff --git a/abilities.lua b/abilities.lua index 3e20226..e4784c5 100644 --- a/abilities.lua +++ b/abilities.lua @@ -240,6 +240,9 @@ robot.add_ability({ return core.get_node(dirPos.frontpos).name end, + runtime_unique = function (part, dir) + return part..dir + end, runtime = true }) @@ -278,6 +281,33 @@ robot.add_ability({ runtime = true }) +-- [[ Speak ]] +robot.add_ability({ + ability = "speak", + item = function () + if core.get_modpath('homedecor') then + return 'homedecor:speaker_driver' + end + return "default:pine_sapling" + end, + act_on = 'last', + depends_on = 'any', + description = S("Send chat messages to the owner"), + command_example = "robot.speak('Hello!')", + done_by = { head = true }, + action = function (nodeinfo, part, message) + local hasability = api.any_has_ability(nodeinfo, 'speak') + if not hasability then return end + + local meta = nodeinfo.meta() + local owner = meta:get_string('player_name') + core.chat_send_player(owner, "[robot] "..message) + + return nil + end, + runtime = true +}) + local function is_default_method(obj, key) local method = obj[key] return (key == 'on_place' and method == core.item_place) diff --git a/api/execute.lua b/api/execute.lua index 5868da1..03aae90 100644 --- a/api/execute.lua +++ b/api/execute.lua @@ -219,16 +219,14 @@ local function save_memory(nodeinfo, mem) end end -local function runtime_ability(nodeinfo, action, part) - local ran = false - local result +local function runtime_ability(nodeinfo, ability, part) + local cached_results = {} return function (...) - if ran then - return result + local unique = ability.runtime_unique and ability.runtime_unique(part or 'main', ...) or part or 'main' + if cached_results[unique] == nil then + cached_results[unique] = ability.action(nodeinfo, part or 'main', ...) end - ran = true - result = action(nodeinfo, part, ...) - return result + return cached_results[unique] end end @@ -277,10 +275,10 @@ local function run_inner(nodeinfo) end end elseif ability.runtime then - commands[ability.ability] = runtime_ability(nodeinfo, ability.action) + commands[ability.ability] = runtime_ability(nodeinfo, ability) for _,part in ipairs(parts) do if commands[part] then - commands[part][ability.ability] = runtime_ability(nodeinfo, ability.action, part) + commands[part][ability.ability] = runtime_ability(nodeinfo, ability, part) end end else