Page 1 of 1

Saving OOP using WriteTable loses Variables?

Posted: Tue Nov 24, 2020 11:55 am
by Bugala
a test code:

Code: Select all



myOOP = {}

Function myOOP:Create()
	o = {}
	SetMetaTable(o, self)
	self.__index = self
	o.varstosave = {}
	o.anothervar = 2
	Return(o)
EndFunction


Function myOOP:Save()
	OpenFile(1, "ooptest.oop", #MODE_WRITE)
	WriteTable(1, self)
	CloseFile(1)
EndFunction

Function myOOP:Load()
	OpenFile(1, "ooptest.oop", #MODE_READ)
	self = ReadTable(1)
	CloseFile(1)
	SetMetaTable(self, GFXPack)
	self.__index = GFXPack
	DebugPrint(self.varstosave.test)
	DebugPrint(self.anothervar)
	Return(self)
EndFunction

testOOP = myOOP:Create()

testOOP.varstosave.test = 1
testOOP.anothervar = 3
testOOP:Save()


secondOOP = myOOP:Create

secondOOP:Load()
DebugPrint(secondOOP.anothervar)
DebugPrint(secondOOP.varstosave.test)
Is this expected behavior?

It seems like for some reason when I am using self = ReadTable, that self is only local and gets destroyed after exiting the function.

I can get around this by using return(self) but this seems odd to me.

Re: Saving OOP using WriteTable loses Variables?

Posted: Tue Nov 24, 2020 4:15 pm
by SamuraiCrow
Where is GFXPack defined?

Re: Saving OOP using WriteTable loses Variables?

Posted: Tue Nov 24, 2020 6:03 pm
by Bugala
Sorry, forgot to replace that. I was using pre-existing code for the sample, but forgot to change that part. Here is hopefully right version now:

Code: Select all

myOOP = {}

Function myOOP:Create()
	o = {}
	SetMetaTable(o, self)
	self.__index = self
	o.varstosave = {}
	o.anothervar = 2
	Return(o)
EndFunction


Function myOOP:Save()
	OpenFile(1, "ooptest.oop", #MODE_WRITE)
	WriteTable(1, self)
	CloseFile(1)
EndFunction

Function myOOP:Load()
	OpenFile(1, "ooptest.oop", #MODE_READ)
	self = ReadTable(1)
	CloseFile(1)
	SetMetaTable(self, myOOP)
	self.__index = myOOP
	DebugPrint(self.varstosave.test)
	DebugPrint(self.anothervar)
	Return(self)
EndFunction

testOOP = myOOP:Create()

testOOP.varstosave.test = 1
testOOP.anothervar = 3
testOOP:Save()


secondOOP = myOOP:Create

secondOOP:Load()
DebugPrint(secondOOP.anothervar)
DebugPrint(secondOOP.varstosave.test)
Anyway, behavior stays the same.

Re: Saving OOP using WriteTable loses Variables?

Posted: Tue Nov 24, 2020 8:46 pm
by SamuraiCrow
It looks like the __index metamethod has a return code required.