Saving OOP using WriteTable loses Variables?

Discuss any general programming issues here
Post Reply
Bugala
Posts: 961
Joined: Sun Feb 14, 2010 7:11 pm

Saving OOP using WriteTable loses Variables?

Post 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.

SamuraiCrow
Posts: 362
Joined: Fri May 15, 2015 5:15 pm
Location: Waterville, Minnesota USA

Re: Saving OOP using WriteTable loses Variables?

Post by SamuraiCrow »

Where is GFXPack defined?
I'm on registered MorphOS using FlowStudio.

Bugala
Posts: 961
Joined: Sun Feb 14, 2010 7:11 pm

Re: Saving OOP using WriteTable loses Variables?

Post 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.

SamuraiCrow
Posts: 362
Joined: Fri May 15, 2015 5:15 pm
Location: Waterville, Minnesota USA

Re: Saving OOP using WriteTable loses Variables?

Post by SamuraiCrow »

It looks like the __index metamethod has a return code required.
I'm on registered MorphOS using FlowStudio.

Post Reply