Skip to content

Commit

Permalink
Added LuaUserData.HasMember and made CreateStatic automatically add c…
Browse files Browse the repository at this point in the history
…all metatable if it the type has a constructor
  • Loading branch information
evilfactory committed Aug 8, 2024
1 parent 496ce0f commit 8d3d01c
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 2 deletions.
17 changes: 15 additions & 2 deletions Barotrauma/BarotraumaShared/Lua/LuaUserData.lua
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ luaUserData.AddField = clrLuaUserData.AddField
luaUserData.RemoveMember = clrLuaUserData.RemoveMember
luaUserData.CreateUserDataFromDescriptor = clrLuaUserData.CreateUserDataFromDescriptor
luaUserData.CreateUserDataFromType = clrLuaUserData.CreateUserDataFromType
luaUserData.HasMember = clrLuaUserData.HasMember

luaUserData.RegisterType = function(typeName)
local success, result = pcall(clrLuaUserData.RegisterType, typeName)
Expand Down Expand Up @@ -50,6 +51,10 @@ luaUserData.AddCallMetaTable = function (userdata)
error("Attempted to add a call metatable to a nil value.", 2)
end

if not LuaUserData.HasMember(userdata, ".ctor") then
error("Attempted to add a call metatable to a userdata that does not have a constructor.", 2)
end

debug.setmetatable(userdata, {
__call = function(obj, ...)
if userdata == nil then
Expand All @@ -68,14 +73,22 @@ luaUserData.AddCallMetaTable = function (userdata)
})
end

luaUserData.CreateStatic = function(typeName, addCallMethod)
luaUserData.CreateStatic = function(typeName)
if type(typeName) ~= "string" then
error("Expected a string for typeName, got " .. type(typeName) .. ".", 2)
end

local success, result = pcall(clrLuaUserData.CreateStatic, typeName)

if not success then
error(result, 2)
end

if addCallMethod then
if result == nil then
return
end

if LuaUserData.HasMember(result, ".ctor") then
luaUserData.AddCallMetaTable(result)
end

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -284,6 +284,38 @@ public static void RemoveMember(IUserDataDescriptor IUUD, string memberName)
descriptor.RemoveMember(memberName);
}

public static bool HasMember(object obj, string memberName)
{
if (obj == null) { throw new ScriptRuntimeException("object is nil"); }

Type type;
if (obj is Type)
{
type = (Type)obj;
}
else if(obj is IUserDataDescriptor descriptor)
{
type = descriptor.Type;

if (((StandardUserDataDescriptor)descriptor).HasMember(memberName))
{
return true;
}
}
else
{
type = obj.GetType();
}

if (type.GetMember(memberName).Length == 0)
{
return false;
}

return true;
}


/// <summary>
/// See <see cref="CreateUserDataFromType"/>.
/// </summary>
Expand Down

0 comments on commit 8d3d01c

Please sign in to comment.