Page 1 of 1

mixins: problem with variables?

PostPosted: Fri Nov 11, 2011 3:12 pm
by callisto
Hi,

I have started to look at mixins. What I am aiming to do is add some implemented methods and perhaps state to a couple of otherwise independent classes. I've hit a problem, which suggests it is not possible to define local variables in a method defined in a mixin. For example:

I create one file 'main.cobra' with the code:
class TestMixin adds MyCode
def main
print "from main"
.hi


and then a file 'mixin.cobra' with the code:
mixin MyCode
def hi
print "hi"


$ cobra mixin.cobra main.cobra

and everything is fine. (Although I went on a little detour in my current project, before realising the order of the files was significant...)

But if I modify the file 'mixin.cobra' to:
mixin MyCode
def hi
myvar = 0
print "hi [myvar]"


Then I get errors on compiling:

$ cobra mixin.cobra main.cobra
main.cobra(3): error: The name "myvar" does not exist in the current context
main.cobra(4): error: The name "myvar" does not exist in the current context
Compilation failed - 2 errors, 0 warnings
Not running due to errors above.

(It is also a little confusing that the errors refer to the file holding the class which adds the mixin.)

Given the above, I've changed my program to use instance variables, but I noticed that a variable defined in a 'using' block, e.g.:
def savePdfAnalysis(filename as String, index as int)
using document = Document()
PdfWriter.getInstance(document, File.create(filename))
document.open
document.add(Paragraph("Analysis of document pair [index]"))


throws a warning:
> warning: The value of variable "document" is never used.
but the program works.

Re: mixins: problem with variables?

PostPosted: Fri Nov 11, 2011 9:21 pm
by Charles
Mix-ins are only partially implement as described here, but I was not expecting these errors. I will take a look.

Re: mixins: problem with variables?

PostPosted: Sat Nov 12, 2011 12:16 pm
by Charles
Fixed.

Re: mixins: problem with variables?

PostPosted: Sun Nov 13, 2011 3:48 am
by callisto
Charles, thanks for the quick fix. That's enough to help me move forward.

For the record, local variables still cause problems if within other blocks. e.g.
mixin MyCode
def hi
myvar = 0
if myvar < 10
inner = 2
print "a [inner]"
else
print "b"


mixin.cobra(3): warning: The value of variable "myvar" is never used.
main.cobra(5): error: The name "inner" does not exist in the current context
main.cobra(6): error: The name "inner" does not exist in the current context
Compilation failed - 2 errors, 1 warning
Not running due to errors above.

Re: mixins: problem with variables?

PostPosted: Sun Nov 13, 2011 7:18 pm
by Charles
Thanks for the report. I fixed the above case and some others. There are still some left, but you should run into this less often. I'll finish the others this week.