Forth expression arithmetic operations - forth

In Java it's possible to do the following:
int var = 5;
var += 2;
var -= 2;
var *= 2;
var /= 2;
Is it possible to do this in Forth?
variable var
3 var !
1 var +! //Increment
Is it possible to do the other operations like that in Forth? If not, any hints on how to?

Except for decrementing with -2 var +!, those other operations are not built in.
You can do this:
: -! ( x addr -- ) swap negate swap +! ;
: *! ( x addr -- ) tuck # * swap ! ;
: /! ( n addr -- ) tuck # / swap ! ;

There is a fundamental reason why this can't be done in Forth.
Let's have
int var, var1 ;
and Jave code :
'var = var1 ;
Apart from the matter that Forth wants the tokens separated by spaces, Forth wants a word always do the same, independant of context.
In the Java code var is a left side and that means it must represent an address, where something is stored.
On the right hand side var1 also represents an address. But Java magically fetches the content of the address! In Forth we don't deal in magic. We can't have it that var is now doing this and then doing that.
The examples that you give are doable as long as you stay clear from the magic parts, as is explained in other answers.
[And of course Forth can also do magic. You could make an =-word that inspects whether the following word var is of type int and then fetches it. But that is not Forth, that is a Forth-implementation of Java.]

Related

Var in var = var in var + 1

I am still new to Lua and have one question about var in var.
How do I calculate this:?
A=1
X=A
X=X+1
As you can see:
This calculation would result in
A=A+1
But this does not work for me.
I guess I have to format the cars in some way.
I want to do this because I want to be able to change a var in another var when necessary.
The = operator does two things:
Evaluate the right-hand side
Assign the result to the variable on the left-hand side
To illustrate, consider this example:
A = 1 -- A is now 1
X = A + A + A -- X is now 3, and A hasn't changed
X = X + 1 -- X is now 4, and A hasn't changed
Now lets look at your original code, and write out the meaning in plain language.
A=1 -- Create a variable 'A' and assign it the value of one
X=A -- Create the variable 'X' and assign it the current value of 'A'
X=X+1 -- Change 'X' by assigning it the current value of 'X' plus one
Notice how these comments read like "instructions" to a computer, rather than math equations. Lua (and programming in general) should be interpreted as a set of instructions executed from top to bottom.
However, as Egor Skriptunoff alludes to in earlier comments, tables behave differently. See Programming in Lua - Chapter 2.5 for a more detailed explanation of how tables are different.

Handling floats in redis

I need to use Redis in a project I am using and was wondering if there was anyway to do proper mathmatic operations and comparisons on floats using LUA scripts(or anyway really). For example, I have a field, and need to multiply it by another field, and compare it to a third field. For example
local staticVal = .2
local dynamicVal2 = redis.pcall('GET', 'dynamicVal2')
local calcVal = dynamicVal * staticVal
local compareVal = 100
if calcVal < compareVal then
return false
else
return true
Is there a possible way to do this, or do I have to just make the GET calls from another language and do the comparison there?
Thank you
Edit:
Or the ability to just compare floating point numbers would be helpful. It seems that a dictionary comparison is done rather than a numerical comparison.
Edit 2:
SET val1 10.5
SET val2 3.5
EVAL "local val1 = redis.pcall('GET','val1'); local val2 = redis.pcall('GET','val2'); if val1 > val2 then return val1 else return val2 end" 0
It seems that a dictionary comparison is done rather than a numerical comparison.
local val1 = redis.pcall('GET','val1');
local val2 = redis.pcall('GET','val2');
if val1 > val2 then ...
Check the type of val1 and val2 (e.g. print(type(val1))). My guess is that they are strings, which is why you're getting a lexical comparison rather than a numerical one.
Lua's native number type is floating point and it has no problem comparing them. If your values are indeed strings, you just need to convert them into numbers (e.g. tonumber(val1)) before comparing them.
Of course you can: in Lua, all the numbers are floats. It is actually more difficult to work with large integer values than with floats (due to the internal numbers representation).
From redis-cli:
set dynamicVal2 100000.0
eval "local staticVal = .2 ; local dynamicVal = tonumber(redis.call('GET', 'dynamicVal2')); local calcVal = dynamicVal * staticVal; local compareVal = 100; if calcVal < compareVal then return false; else return true; end;" 0
(integer) 1
Now using Lua for the example you gave is not that useful: what is done with Lua on server-side could be easily done on client-side with similar efficiency. And it is actually better to do it on client-side if you can. Like with many other data stores, the more you can do on client-side for the same number of roundtrips, the best it is.
It would have been more useful if the Lua script was effectively used to avoid multiple roundtrips to Redis.

Implementing post / pre increment / decrement when translating to Lua

I'm writing a LSL to Lua translator, and I'm having all sorts of trouble implementing incrementing and decrementing operators. LSL has such things using the usual C like syntax (x++, x--, ++x, --x), but Lua does not. Just to avoid massive amounts of typing, I refer to these sorts of operators as "crements". In the below code, I'll use "..." to represent other parts of the expression.
... x += 1 ...
Wont work, coz Lua only has simple assignment.
... x = x + 1 ...
Wont work coz that's a statement, and Lua can't use statements in expressions. LSL can use crements in expressions.
function preIncrement(x) x = x + 1; return x; end
... preIncrement(x) ...
While it does provide the correct value in the expression, Lua is pass by value for numbers, so the original variable is not changed. If I could get this to actually change the variable, then all is good. Messing with the environment might not be such a good idea, dunno what scope x is. I think I'll investigate that next. The translator could output scope details.
Assuming the above function exists -
... x = preIncrement(x) ...
Wont work for the "it's a statement" reason.
Other solutions start to get really messy.
x = preIncrement(x)
... x ...
Works fine, except when the original LSL code is something like this -
while (doOneThing(x++))
{
doOtherThing(x);
}
Which becomes a whole can of worms. Using tables in the function -
function preIncrement(x) x[1] = x[1] + 1; return x[1]; end
temp = {x}
... preincrement(temp) ...
x = temp[1]
Is even messier, and has the same problems.
Starting to look like I might have to actually analyse the surrounding code instead of just doing simple translations to sort out what the correct way to implement any given crement will be. Anybody got any simple ideas?
I think to really do this properly you're going to have to do some more detailed analysis, and splitting of some expressions into multiple statements, although many can probably be translated pretty straight-forwardly.
Note that at least in C, you can delay post-increments/decrements to the next "sequence point", and put pre-increments/decrements before the previous sequence point; sequence points are only located in a few places: between statements, at "short-circuit operators" (&& and ||), etc. (more info here)
So it's fine to replace x = *y++ + z * f (); with { x = *y + z * f(); y = y + 1; }—the user isn't allowed to assume that y will be incremented before anything else in the statement, only that the value used in *y will be y before it's incremented. Similarly, x = *--y + z * f(); can be replaced with { y = y - 1; x = *y + z * f (); }
Lua is designed to be pretty much impervious to implementations of this sort of thing. It may be done as kind of a compiler/interpreter issue, since the interpreter can know that variables only change when a statement is executed.
There's no way to implement this kind of thing in Lua. Not in the general case. You could do it for global variables by passing a string to the increment function. But obviously it wouldn't work for locals, or for variables that are in a table that is itself global.
Lua doesn't want you to do it; it's best to find a way to work within the restriction. And that means code analysis.
Your proposed solution only will work when your Lua variables are all global. Unless this is something LSL also does, you will get trouble translating LSL programs that use variables called the same way in different places.
Lua is only able of modifying one lvalue per statement - tables being passed to functions are the only exception to this rule. You could use a local table to store all locals, and that would help you out with the pre-...-crements; they can be evaluated before the expression they are contained in is evauated. But the post-...-crements have to be evaluated later on, which is simply not possible in lua - at least not without some ugly code involving anonymous functions.
So you have one options: you must accept that some LSL statements will get translated to several Lua statements.
Say you have a LSL statement with increments like this:
f(integer x) {
integer y = x + x++;
return (y + ++y)
}
You can translate this to a Lua statement like this:
function f(x) {
local post_incremented_x = x + 1 -- extra statement 1 for post increment
local y = x + post_incremented_x
x = post_incremented_x -- extra statement 2 for post increment
local pre_incremented_y = y + 1
return y + pre_incremented_y
y = pre_incremented_y -- this line will never be executed
}
So you basically will have to add two statements per ..-crement used in your statements. For complex structures, that will mean calculating the order in which the expressions are evaluated.
For what is worth, I like with having post decrements and predecrements as individual statements in languages. But I consider it a flaw of the language when they can also be used as expressions. The syntactic sugar quickly becomes semantic diabetes.
After some research and thinking I've come up with an idea that might work.
For globals -
function preIncrement(x)
_G[x] = _G[x] + 1
return _G[x]
end
... preIncrement("x") ...
For locals and function parameters (which are locals to) I know at the time I'm parsing the crement that it is local, I can store four flags to tell me which of the four crements is being used in the variables AST structure. Then when it comes time to output the variables definition, I can output something like this -
local x;
function preIncrement_x() x = x + 1; return x; end
function postDecrement_x() local y = x; x = x - 1; return y; end
... preIncrement_x() ...
In most of your assessment of configurability to the code. You are trying to hard pass data types from one into another. And call it a 'translator'. And in all of this you miss regex and other pattern match capacities. Which are far more present in LUA than LSL. And since the LSL code is being passed into LUA. Try using them, along with other functions. Which would define the work more as a translator, than a hard pass.
Yes I know this was asked a while ago. Though, for other viewers of this topic. Never forget the environments you are working in. EVER. Use what they give you to the best ability you can.

Lua base converter

I need a base converter function for Lua. I need to convert from base 10 to base 2,3,4,5,6,7,8,9,10,11...36 how can i to this?
In the string to number direction, the function tonumber() takes an optional second argument that specifies the base to use, which may range from 2 to 36 with the obvious meaning for digits in bases greater than 10.
In the number to string direction, this can be done slightly more efficiently than Nikolaus's answer by something like this:
local floor,insert = math.floor, table.insert
function basen(n,b)
n = floor(n)
if not b or b == 10 then return tostring(n) end
local digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
local t = {}
local sign = ""
if n < 0 then
sign = "-"
n = -n
end
repeat
local d = (n % b) + 1
n = floor(n / b)
insert(t, 1, digits:sub(d,d))
until n == 0
return sign .. table.concat(t,"")
end
This creates fewer garbage strings to collect by using table.concat() instead of repeated calls to the string concatenation operator ... Although it makes little practical difference for strings this small, this idiom should be learned because otherwise building a buffer in a loop with the concatenation operator will actually tend to O(n2) performance while table.concat() has been designed to do substantially better.
There is an unanswered question as to whether it is more efficient to push the digits on a stack in the table t with calls to table.insert(t,1,digit), or to append them to the end with t[#t+1]=digit, followed by a call to string.reverse() to put the digits in the right order. I'll leave the benchmarking to the student. Note that although the code I pasted here does run and appears to get correct answers, there may other opportunities to tune it further.
For example, the common case of base 10 is culled off and handled with the built in tostring() function. But similar culls can be done for bases 8 and 16 which have conversion specifiers for string.format() ("%o" and "%x", respectively).
Also, neither Nikolaus's solution nor mine handle non-integers particularly well. I emphasize that here by forcing the value n to an integer with math.floor() at the beginning.
Correctly converting a general floating point value to any base (even base 10) is fraught with subtleties, which I leave as an exercise to the reader.
you can use a loop to convert an integer into a string containting the required base. for bases below 10 use the following code, if you need a base larger than that you need to add a line that mapps the result of x % base to a character (usign an array for example)
x = 1234
r = ""
base = 8
while x > 0 do
r = "" .. (x % base ) .. r
x = math.floor(x / base)
end
print( r );

ActionScript3 sign-extension with indexed access to ByteArray

In the following code:
var bytes:ByteArray = new ByteArray();
var i:int = -1;
var j:int;
bytes[0] = i; // bytes[0] = -1 == 0xff
j = bytes[0]; // j == 255;
The int j ends up with value 255, rather than -1. I can't seem to find a document defining how indexed access to a ByteArray is supposed to be sign extended - can I reliably assume this behavior, or should I take steps to truncate such values to 8 bit quantities? I'm porting a bunch of code from Java and would prefer to use the indexed access rather that the readByte() etc methods.
The IDataInput interface (implemented by ByteArray) says:
Sign extension matters only when you read data, not when you write it. Therefore you do not need separate write methods to work with IDataInput.readUnsignedByte() and IDataInput.readUnsignedShort().
The same would naturally apply to [] array access, so you wouldn't need to truncate before writing.
I can't see any explicit documentation of that, and nothing that states that array read access is unsigned. If you wanted to ensure that read access gave you an unsigned value back you could say:
j= j<<24>>>24;
and similarly with >> for signed. However with ActionScript being a single implementation, not a general standard, you probably don't have to worry about it

Resources