albertodemichelis / squirrel

Official repository for the programming language Squirrel
http://www.squirrel-lang.org
MIT License
912 stars 156 forks source link

Confusion with "type vs typeof" usage #281

Open XandrosDarkstorm opened 9 months ago

XandrosDarkstorm commented 9 months ago

Hello. I am trying to understand the difference between calling type and typeof in Squirrel 3.0.7 and i am having a hard time. Here is what i gathered so far:

type

typeof

I used this code:

s <- {
    _typeof = function()
    {
    return "mycooltable"
    }
}

local t = {}
local a = ["first","second","third"]
//creates a weakref to the array and assigns it to a table slot
t.thearray <- a.weakref();

print("_typeof test\n")
print(type(s) + "\n")
print((typeof s) + "\n")

print("=====\nweakref test\n")
print(type(t.thearray) + "\n")
print((typeof t.thearray) + "\n")

Please, help me understand: am i doing something wrong here or is it a bug?

zeromus commented 9 months ago

You didn't explain what you think the bugs are, but I can guess. Bug 1 (line 3 of output): you are not setting the metamethods correctly. setdelegate() is required. This is squirrel 101 Bug 2 (lines 5 and 6): t.thearray is an array because the table get dereferences the weak reference so you can use it without knowing that it's a weak reference. if it were otherwise, t.thearray[0] would be nonsense because myweakref[0] is nonsense. What you want is t.thearray.weakref() which seems a bit crazy (is it a weakref to a weakref?) but no, it's the weakref itself (check SQRefCount::GetWeakRef() which returns the thing itself it it's actually a weakref). I don't blame you for getting this one wrong.

XandrosDarkstorm commented 9 months ago

@zeromus Thank you for the explanation. I think i now understand what was wrong with my code. Weakref stuff was directly copy-pasted from the official documentation. Maybe this weakref.weakref() stuff needs to be mentioned there/corrected. Anyways, thanks again for your help.

zeromus commented 9 months ago

hmmmm can you quote the exact part of docs at which URL?

XandrosDarkstorm commented 9 months ago

http://www.squirrel-lang.org/doc/squirrel3.html#weakrefs

The code examples from gray zones never show "t.thearray.weakref()". It feels as if t.thearray is supposed to be its own object with "weakref" type.

zeromus commented 9 months ago

Yes, that's what one would expect. But the docs say otherwise:

The table slot 'thearray' contains a weak reference to an array. The following line prints "first", because tables(and all other containers) always return the object pointed by a weak ref

t.theArray is "the object pointed to by a weak ref", not, "the weak ref".

This is SNEAKY and the docs could probably explain it better. But they do explain it. They would explain it better with a weakref.weakref() example which would alert pretty much any reader to the complication of it all.

Sorry to all, I don't have suggested alternative docs at this moment.