left arrow key turns on keycode 37 and 39 - keycode

I am trying to program a simple pong program that uses arrow keys to navigate the player's paddle. I need to check instantaneous keycodes so I made a separate js file to parse the onkeydown and onkeyup events as booleans for the keycodes that I need. However, when I type the left arrow it turns on keycodes 37 and 39 together. This doesn't work for the right arrow but I have had it before confuse the space bar as an arrow key. The code basically looks like this:
var KeyPressed=
{
Left:false,
Right:false,
...
};
window.onkeydown =function(e) {
e = e || window.event;
var getKey = e.keyCode ? e.keyCode:e.charCode;
switch (getKey) {
case 37: KeyPressed.Left=true;
case 39: KeyPressed.Right=true;
...
}
};
window.onkeyup = function(e){
e = e || window.event;
var getKey = e.keyCode ? e.keyCode:e.charCode;
switch (getKey){
case 37: KeyPressed.Left=false;
case 39: KeyPressed.Right=false;
...
}
};

It looks like you're not resetting the left/right boolean status per press. So you should probably onkeyup set both to false regardless.

Related

Figure doesn't show correct string on event

In the following code I create 3 boxes with the text 1 to 3, in a fourth box I'd like to show the text of the box my mouse is hovering over. So i set an onMouseEnter FProperty for each of the boxes where I change the string of the fourth box and tell it to redraw.
bool redraw = false;
str s = "0";
Figure getTextbox() {
return computeFigure(bool() {bool temp = redraw; redraw = false; return temp; },
Figure() {
return text(str() {return s; });
});
}
list[Figure] boxes = [];
for (i <- [1..4]) {
boxes += box(text(toString(i)), onMouseEnter(void () {s = toString(i); redraw = true; }));
}
Figure changer = box(getTextbox());
render(vcat(boxes + changer));
However, for some odd reason all three boxes will tell the onMouseEnter method to change the text of the fourth box into "3" (the value of the last box) instead of their individual value.
Any clue why? Thanks!
Ah yes, this is the variable capturing closure problem with for loops, also known from other languages which have this particular feature like Javascript. This is the code with the issue:
for (i <- [1..4]) {
boxes += box(text(toString(i)), onMouseEnter(void () {s = toString(i); redraw = true; }));
}
The variable i is bound by the void closure and not its value. So every time the function which is created and passed to onMouseEnter it will read the latest value of the i variable. Since the callback is called after the loop terminates, all calls to the mouse enter function will have the value 3.
To fix this and "do what you want", the following code would work I believe:
for (i <- [1..4]) {
newS = toString(i);
boxes += box(text(toString(i)), onMouseEnter(void () {s = newS; redraw = true; }));
}
This works because for every pass of the for loop a new environment is created which binds the newS variable. So you'll get a fresh newS for every loop instead of the reused i.

What is the alternative for switch statement in Lua language?

I have this piece of code in C++ and i want to know how can i write some codes that replace switch statement in Lua because i face many problems and i need to use this statement.
int choice;
do// loop
{
cout<<"\n >>> The General Menu <<< \n";
cout << endl;
cout<< " press (1) to Add "<<endl;
cout<< " press (2) to Save "<<endl;
cout<< " press (3) to Quit " << endl;
cout<< endl;
cout<< "Enter your choice please (1/2/3): ";
cin>>choice;
switch(choice)
{
case 1:
add();
break;
case 2:
save();
break;
default:
cout<<" The program has been terminated "<<endl;
cout<<" Thank you! \n";
}
} while (choice != 3);
}
The statement has been used inside a do..while loop.
In general, if you want a switch statement in Lua, what you ought to be doing is building a table. For your simple case of choice that could be 1, 2, or fail, a simple if statement with a few conditions is sufficient. For more complex cases, a table of functions should be employed:
local c_tbl =
{
[1] = add,
[2] = save,
}
local func = c_tbl[choice]
if(func) then
func()
else
print " The program has been terminated."
print " Thank you!";
end
You can use lexical scoping to allow the functions in the table to be able to access local variables, just as if the code was written inline.
Try this one (click here to run the script in a Lua compiler), Hope the code is self-explanatory ;-) and
resembles the same pseudo code format..!!
print("enter your choice : ")
mychoice = io.read()
switch = function (choice)
-- accepts both number as well as string
choice = choice and tonumber(choice) or choice -- returns a number if the choic is a number or string.
-- Define your cases
case =
{
[1] = function ( ) -- case 1 :
print("your choice is Number 1 ") -- code block
end, -- break statement
add = function ( ) -- case 'add' :
print("your choice is string add ") -- code block
end, -- break statement
['+'] = function ( ) -- case '+' :
print("your choice is char + ") -- code block
end, -- break statement
default = function ( ) -- default case
print(" your choice is din't match any of those specified cases")
end, -- u cant exclude end hear :-P
}
-- execution section
if case[choice] then
case[choice]()
else
case["default"]()
end
end
-- Now you can use it as a regular function. Tadaaa..!!
switch(mychoice)
Lua:
if choice == 1
then add()
elseif choice == 2
then save()
else print "The program has been terminated\nThank you!"
end
one more version of switcher (without initializing table as variable):
local case=2;
local result=({[1]="case1", [2]="case2", 3="case3"})[case];
print (result); --> case2
While simply creating a table indexed by cases with functions as elements is most probably the fastest approach, there is this solution I've made which IMO has better code readability:
function switch(element)
local Table = {
["Value"] = element,
["DefaultFunction"] = nil,
["Functions"] = {}
}
Table.case = function(testElement, callback)
Table.Functions[testElement] = callback
return Table
end
Table.default = function(callback)
Table.DefaultFunction = callback
return Table
end
Table.process = function()
local Case = Table.Functions[Table.Value]
if Case then
Case()
elseif Table.DefaultFunction then
Table.DefaultFunction()
end
end
return Table
end
Example Use:
switch(Player:GetName())
.case("Kate", function() print("This player's name rhymes with Fate")end)
.case("Tod", function() print("This player's name rhymes with Cod") end)
.default(function() print("This player's name is not Kate or Tod") end)
.process()
I encountered this issue with functions that would take different parameters - something which the other answers don't handle well.
I solved that with anonymous functions.
-- call the relevant execution based on its opcode
local instructions = {
[01] = function () self:perform_add(table.unpack(valargs)) end,
[02] = function () self:perform_multiply(table.unpack(valargs)) end,
[03] = function () self:perform_store_input(outputargs[1]) end,
[04] = function () self:perform_output(valargs[1]) end,
[05] = function () self:perform_jnz(table.unpack(valargs)) end,
[06] = function () self:perform_jz(table.unpack(valargs)) end,
[07] = function () self:perform_less_than(table.unpack(valargs)) end,
[08] = function () self:perform_equals(table.unpack(valargs)) end,
[99] = function () self:perform_exit() end,
}
local instr = instructions[opcode]
if (instr) then
instr()
else
print("No instruction for opcode " .. opcode)
end
The actions I want to take in my different switch cases are all defined as anonymous functions in a table. The keys used (e.g. 08 here) are the values our variable to switch on might assume (opcode here). The default case of the switch statement happens in my else clause. There is no requirement for a break equivalent - but if you want to have one case continue with the next you would have to call it explicitly.
Reply to comment asking for clarification:
You're right that this example is not complete. You can find my usage here when I did adventofcode 2019 day 7. I can try answer your questions but I never touched lua before, and never after. valargs is a table of arguments because different functions here take different numbers of arguments. But that is not necessarily relevant to the question. Basically, I'm just calling functions here.
In my example, self exists because I defined the functions on a local (and did some weird changes as outlined here). The relevant code parts:
-- a "class"
local IntComputer = {}
function IntComputer:perform_exit()
self.program_ended = true
end
function IntComputer:perform_add(a, b, target)
print(" " .. a .. " + " .. b .. " => " .. target)
self:set_value(target, a+b)
end
If you want switch as a function that is callable, you could use something funny with the callback feature:
(The example below is a switch statement based on the variable type, but you could make the table index into whatever you want to test it for. Just change the return statement of the switch function to not test for type(case))
(This is essentially a lazy table lookup much like Python's dictionary feature but each element is a function)
#!/usr/bin/lua
-- Callback switch statement:
local function switch(a, case)
-- Local variable instead of function(a) on every case:
local value = a
-- Cases list:
local switchcase = {}
-- Cases:
switchcase["string"] = function()
return (tostring(value) .. " is a string")
end
switchcase["number"] = function()
return tostring(value .. " is a number")
end
switchcase["boolean"] = function()
return (tostring(avalue) .. " is a boolean")
end
return switchcase[type(case)](a)
end
local value = 5
print(switch(value,value)) --> 5 is a number
local value = "test"
print(switch(value,value)) --> test is a string
local value = true
print(switch(value,value)) --> true is a boolean
I don't know the performance of this code compared to the two answers given above, but using local variables ought to make it quick enough for repeated use. If you make your switch function in the global scope it could become a standard function for your project to be used.
Here's another fun method using loadstring() and a table lookup.
switch = function(cases,args)
if (cases[args] == nil) then return args else return assert(loadstring ('return ' .. cases[args]))() end
end
local case = 2
local result = switch({
[1] = "2^" .. case,
[2] = string.format("2^%i",case),
[3] = tostring(2^case)
},
case
)
print(result) --> 4
This method is somewhat dangerous to use since loadstring() is similar to Python's eval() function.
I found it ugly to write "function(x)" on every case in the examples provided by the Lua wiki. This is a neat way.
The "default" case is the "return args" part of the function.
I use this code :
while true do local tmpswitch1 = exp ; --[[ switch <exp> do ]]
if tmpswitch1 == exp1 then --[[ case <exp1> : ]]
-- do something
break
end ;if tmpswitch1 == exp2 then --[[ case <exp2> : ]]
-- do something
break
end ; --[[ default : ]]
-- do something
break ; end --[[ switch tmpswitch1 ]]
function case(i,d) return function(t) return t[i] or d end end
x='two'
r=case(x) {
one=1,
two=2,
three=3,
}
case(r,function() print "default" end) {
[1]=function() print "one" end,
[2]=function() print "two" end,
[3]=function() print "three" end,
}()

How to set the popUp Panel show at the position of mouse cursor in richFaces

Is there any Attributes to be able to put popup panel show in the position of the mouse cursor in richFaces 4.?
I now think of one solution is to impact on the show event in rich: component (). Show() function, set the location for the popup by javascript.
You can directly handle the showing of a richfaces modal panel through javascript as shown Here
this js function below will give you the x/y coordinate position of the mouse pointer, the return value of which you can pass as arguments to the Richfaces.showModalPanel function
function getPosition(e) {
e = e || window.event;
var cursor = {x:0, y:0};
if (e.pageX || e.pageY) {
cursor.x = e.pageX;
cursor.y = e.pageY;
}
else {
var de = document.documentElement;
var b = document.body;
cursor.x = e.clientX +
(de.scrollLeft || b.scrollLeft) - (de.clientLeft || 0);
cursor.y = e.clientY +
(de.scrollTop || b.scrollTop) - (de.clientTop || 0);
}
return cursor;
}
so you can have RichFaces.showModalPanel('panel',{top:getPosition(ev).y,left:getPosition(ev).x})
Sorry about the hideous javascript.

How to align a struct member in D?

I tried this
struct Foo(T)
{
align(8) void[T.sizeof] data;
}
but
static assert(Foo!(int).data.alignof == 8);
fails, telling me the alignment is still 1 instead of 8.
Why is this, and how do I fix it, so that it works for any arbitrary alignment that is a power of 2 (not just 8)?
Browsing the DMD source, it looks like alignof doesn't take into account align attributes.
Here is where it is handled:
... if (ident == Id::__xalignof)
{
e = new IntegerExp(loc, alignsize(), Type::tsize_t);
}
This converts a .alignof expression into a size_t expression with value alignsize(), so let's look at alignsize() for a static array:
unsigned TypeSArray::alignsize()
{
return next->alignsize();
}
It just gets the alignment of the element type (void) in your case.
void is handled by TypeBasic::alignsize(), which just forwards to TypeBasic::size(0)
switch (ty)
{
...
case Tvoid:
size = 1;
break;
...
}
Looking at how other types handle alignof, it doesn't look like align attributes are taken into account at all, but I could be wrong. It may be worth testing the alignment manually.

jquery ui dialog loses values on second call (IE8)

I have a page which has 16 buttons. When clicked a dialog opens and a user can select various select elements (an item, an operator, and a value).
This works great in FF but not so good in IE8.
User clicks button 1, enters data, closes the dialog (FF, IE8 Good)
User clicks button 2, enters data, closes the dialog (FF, IE8 Good)
User clicks button 2 again, enters data, closes the dialog (FF Good), (IE8 fails)
The problem only happens if a user clicks the same button in succession (note two instances are not opened both at the same time: user clicks button 2, processes it, closes it then clicks button 2 a few moments later).
The problem is to do with the script losing the form values.
When the button is clicked the following vars are set:
var item = $("#name-item"),operator = $("#name-operator")
item will be something like "-tNAME", operator something like "eq="
on the second run $("#name-item") and $("#name-operator") are blank so this sounds like a declaration / initialization problem but where?
dialog code:
$("#dialog-form-name").dialog({autoOpen:false,height:450,width:350,modal:false,position:[675,200],buttons: {
'Add Name Filter': function() {
var item = $("#name-item"),operator = $("#name-operator"),value = $("#name-value"),disp=$('#name-item option:selected').text(),join = $("#name-join"),tn = $("#name-item").val().substr(0,2);
var allFields = $([]).add(item).add(operator).add(value).add(join),tips = $(".validateTips"),bValid = true;
allFields.removeClass('ui-state-error');
bValid = bValid && checkLength(value,"value",1,255);
bValid = bValid && checkRegexp(value,/^([\ \.\,\'\(\)0-9a-z_])+$/i,"Value may consist of a-z, 0-9, underscores, commas, spaces");
if(bValid) { updateTableRow('name',item,operator,value,join,disp,tn);$(this).dialog('close'); }
},
Cancel: function() { if(form_status == 'edit') { form_status = 'new';$('#' + rowid).removeClass('ui-state-highlight'); }$(this).dialog('close');$('#form-name')[0].reset();$('#form-name').removeClass('ui-state-error');}},
close: function() { if(form_status == 'edit') { form_status = 'new';$('#' + rowid).removeClass('ui-state-highlight'); }$('#form-name')[0].reset();$('#form-name').removeClass('ui-state-error');$(".validateTips").html();}
});
$("#dialog-form-course").dialog({autoOpen:false,height:450,width:350,modal:false,position:[675,200],buttons: {
'Add Course Filter': function() {
var item = $("#course-item"),value = $("#course-value"),join = $("#course-join"),disp=$('#course-item option:selected').text(),tn = $("#course-item").val().substr(0,2);
if(tn == '-n') { var operator = $("#course-operator-n"); } else { var operator = $("#course-operator-t"); }
var allFields = $([]).add(item).add(operator).add(value).add(join),tips = $(".validateTips"),bValid = true;
allFields.removeClass('ui-state-error');
bValid = bValid && checkLength(value,"value",1,255);
bValid = bValid && checkRegexp(value,/^([\ \.\,\'\(\)0-9a-z_])+$/i,"Value may consist of a-z, 0-9, underscores, commas, spaces");
if(operator.val() == 'beBetween') { if(checkRegexp(value,/[0-9]\ and\ [0-9]/i,"Value must have ' and ' between a range of numbers. Please see example below.") == false) { bValid = false;$("#example-course").html('<br /><em>Example:</em> ' + disp + ' Between 1 <strong>and</strong> 3'); } }
if(bValid) { updateTableRow('course',item,operator,value,join,disp,tn);$(this).dialog('close'); }
},
Cancel: function() { if(form_status == 'edit') { form_status = 'new';$('#' + rowid).removeClass('ui-state-highlight'); }$(this).dialog('close');$('#form-course')[0].reset();$('#form-course').removeClass('ui-state-error');}},
close: function() { if(form_status == 'edit') { form_status = 'new';$('#' + rowid).removeClass('ui-state-highlight'); }$('#form-course')[0].reset();$('#form-course').removeClass('ui-state-error');$(".validateTips").html('Choose an item to filter such as Course, Grade or Direction<br />An operator such as = or a Between range<br />Value such as an individual course, list of courses or value such as Left.');}
});
buttons code:
$('#add-name').button({icons: {primary:'ui-icon-plus'}}).click(function(){form_status == 'new';$('#dialog-form-name').dialog('open');return false;});
$('#add-course').button({icons: {primary:'ui-icon-plus'}}).click(function(){$("#course-operator-t").show();$("#course-operator-n").hide();$("#course-value").autocomplete("option","disabled",false);$('#dialog-form-course').dialog('open');return false;});
You can see the problem here.
In IE click on NAME and then enter anything in the value box and save it. Now click on NAME and do the same again. As soon as you enter anything IE fails because it can not read $("#name-operator")
Finally worked this out.
in the close: function I had
$('#form-name')[0].reset();
This is to reset the form back to defaults after data was entered. In IE it totally wipes sets the form to null values, whilst in firefox it just resets it.
Had to change it to:
$('#form-name :text').val('');
for the text fields and reset the select id for the select options.

Resources