LCB: Complex statement help needed in LCB

Peter TB Brett peter.brett at livecode.com
Tue Mar 1 16:30:55 EST 2016


On 01/03/2016 21:14, Stephen MacLean wrote:

> Thanks:) Being strongly typed has it’s plusses and minuses. I was
> hoping to avoid “parsed as number” by using the “any” type.
>
> It looks like that when you have a variable in LCB with a type of
> “any” and perform an action on it, it becomes that type. So perform
> “put the number of chars in tCardNum into tLen” and tCardNum becomes
> a string type. Do "put 0 into tCheckSum” and tCheckSum becomes a
> number.

It's a bit better to think of pegs (values) and holes (slots).  If you 
write:

    variable tStringVar as String

then you're creating a "String-shaped hole".  It'll only let you put a 
"String-shaped peg" into it, i.e. a value of type String.

If you did:

    put 5 into tStringVar

then you get an error -- you're "putting a square peg into a round 
hole", as it were.

The "any" metatype is a bit special, because it only applies to slots. 
There's no such thing as a value of type "any".  Also, note that you 
can't put the "nothing" value into a slot of type "any".

Going to your examples:

    variable tCardNum as any
    variable tLen as any
    put (the number of chars in (tCardNum)) into tLen

I've added some parentheses to show how evaluation proceeds.  First 
"tCardNum" is evaluated, producing a value $1.  Next, "the number of 
chars in $1" is evaluated.  If the value $1 is a String, then it 
produces a value $2 (which happens to be always a Number).  Otherwise, 
it generates an error.  Finally, "put $2 into tLen" is evaluated.  Since 
$2 is a value of type Number, and tLen is a slot of type "any", they're 
compatible, and the assignment works.  The result is that tLen, a slot 
of type any, contains a value of type Number.

Note that nothing about that statement changes the type of tCardNum (or 
the value it contains).

    variable tCheckSum as any
    put 0 into tCheckSum

First "0" is evaluated, producing $1 (a value of type Number).  Next, 
"put $1 into tCheckSum" is evaluated.  Since $1 is a value of type 
Number, and tCheckSum is a slot of type any, the assignment is 
permitted.  The result is the same: tCheckSum, a slot of type any, 
contains a value of type Number (i.e. tCheckSum is 0).

> I'll give it a go. While I could just wrap the whole thing up and
> execute it as a script, I’m really trying to do as much as possible
> in LCB to learn.

Yes.  I quite like programming in LCB because the compiler helps catch 
(some) silly mistakes.  However, there are some things that are 
difficult (or impossible) using only LCB.  Hopefully, that will be dealt 
with over time!

                                      Peter

-- 
Dr Peter Brett <peter.brett at livecode.com>
LiveCode Open Source Team

LiveCode 2016 Conference https://livecode.com/edinburgh-2016/




More information about the use-livecode mailing list