Created
March 31, 2015 15:52
-
-
Save xanathar/66ffe4a5a367d69fa63d to your computer and use it in GitHub Desktop.
Extend MoonSharp userdata at script runtime
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MyObject | |
{ | |
public int GetSomething() | |
{ | |
return 10; | |
} | |
} | |
[Test] | |
public void MetatableExtensibleObjectSample() | |
{ | |
string code = @" | |
--declare this once for all | |
extensibleObjectMeta = { | |
__index = function(t, name) local obj = rawget(t, 'wrappedobj'); if (obj) then return obj[name]; end end | |
} | |
-- create a new wrapped object called myobj, wrapping the object o | |
myobj = { wrappedobj = o }; | |
setmetatable(myobj, extensibleObjectMeta); | |
function myobj.extended() | |
return 12; | |
end | |
return myobj.extended() * myobj.getSomething(); | |
"; | |
Script script = new Script(); | |
UserData.RegisterType<MyObject>(); | |
script.Globals["o"] = new MyObject(); | |
DynValue res = script.DoString(code); | |
Assert.AreEqual(DataType.Number, res.Type); | |
Assert.AreEqual(120, res.Number); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment