Userdata setters and getters

  • Lets add an CString called MyString to our Vector class. Once again, these are created for you.
#define YS_USERDATA_SET(fn) void fn(Instance* ysi, void* ptr, Variable* var)
#define YS_USERDATA_GET(fn) Variable* fn(Instance* ysi, void* ptr)

YS_USERDATA_SET(CVectorMyStringSet){
  • Variable has functions like GetString, it has a type check inside to make sure it wont crash when you use ->GetString on them. However, It wont throw an error for you. So we’ll have to do that ourselfs by calling this function, which will do that work for you
if (!args->CheckType(0, VariableType::String)) return null;
  • Be sure to copy the value here, because the moment the variable gets cleaned by the GC, the var->Value will get deleted In case you want to keep some data, like tables, use var->IncreaseRefCount() on it to prevent it from getting garbage collected. (REMEMBER TO DO var->DecreaseRefCount()!)
(Scratch::CString*)ptr = Scratch::CString(var->GetString());
}
YS_USERDATA_GET(CVectorMyStringGet){
  • Cast it to our string class
Scratch::CString str = (Scratch::CString*)ptr;
  • You can return null here too.
        return Converter::ToVariable(str);
}
  • And then we add this to our code
ud->RegisterMember("MyString", offsetof(CVector, MyString), MemberType::String, CVectorMyStringSet, CVectorMyStringGet);
  • And now, we can do this: vecobj.MyString = "woo"