Skip to content

Commit 40f3101

Browse files
committed
Get component values with correct type
#9
1 parent e8c6c8b commit 40f3101

File tree

1 file changed

+24
-2
lines changed

1 file changed

+24
-2
lines changed

files/noita-api.lua

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,12 +34,32 @@ NoitaComponent.__index = NoitaComponent
3434
-- JSON Implementation --
3535
-------------------------
3636

37+
-- Set of component keys that would return an "invalid type" error when called with ComponentGetValue2().
38+
-- This is more or less to get around console error spam that otherwise can't be prevented when iterating over component members.
39+
-- Only used inside the JSON marshaler, until there is a better solution.
40+
local componentValueKeysWithInvalidType = {}
41+
3742
---MarshalJSON implements the JSON marshaler interface.
3843
---@return string
3944
function NoitaComponent:MarshalJSON()
45+
-- Get list of members, but with correct type (instead of string values).
46+
local membersTable = self:GetMembers()
47+
local members = {}
48+
if membersTable then
49+
for k, v in pairs(membersTable) do
50+
if not componentValueKeysWithInvalidType[k] then
51+
members[k] = self:GetValue(k) -- Try to get value with correct type. Assuming nil is an error, but this is not always the case... meh.
52+
end
53+
if members[k] == nil then
54+
componentValueKeysWithInvalidType[k] = true
55+
--members[k] = v -- Fall back to string value of self:GetMembers().
56+
end
57+
end
58+
end
59+
4060
local resultObject = {
4161
typeName = self:GetTypeName(),
42-
members = self:GetMembers(),
62+
members = members,
4363
--objectMembers = component:ObjectGetMembers
4464
}
4565

@@ -419,9 +439,11 @@ end
419439

420440
---Returns one or many values matching the type or subtypes of the requested field in a component subobject.
421441
---Reports error and returns nil if the field type is not supported or 'object_name' is not a metaobject.
442+
---
443+
---Reporting errors means that it spams the stdout with messages, instead of using the lua error handling. Thanks Nolla.
422444
---@param objectName string
423445
---@param fieldName string
424-
---@return any
446+
---@return any|nil
425447
function NoitaComponent:ObjectGetValue(objectName, fieldName)
426448
return ComponentObjectGetValue2(self.ID, objectName, fieldName)
427449
end

0 commit comments

Comments
 (0)