Get String Value of passed ByRef Variable - Stack Overflow
文章推薦指數: 80 %
ahk 002: myvar := "george" 003: passit(myvar) 007: MsgBox,GetOriginalVariableNameForSingleArgumentOfCurrentCall(A_ThisFunc) 012: lines := ListLines() Press [F5] ... Home Public Questions Tags Users Companies Collectives ExploreCollectives Teams StackOverflowforTeams –Startcollaboratingandsharingorganizationalknowledge. CreateafreeTeam WhyTeams? Teams CreatefreeTeam Collectives™onStackOverflow Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost. LearnmoreaboutCollectives Teams Q&Aforwork Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch. LearnmoreaboutTeams GetStringValueofpassedByRefVariable AskQuestion Asked 8years,2monthsago Modified 8years,2monthsago Viewed 2ktimes 2 SayIcallafunctionthatusesabyrefmodifier.Onceinthefunction,Iwanttofetchthestringvalueofthepassedvariable. myvar:="george" passit(myvar) passit(byrefwhatvar){ msgbox%%whatvar%;Ishouldseeamessageboxreportingthestring"myvar" } GettingthestringvalueofthevariableworksfineifI'mnotpassingthevariablebyref. MaybeI'mgoingaboutthisthewrongway.Iwantthefunctiontoknowthestringnameforthevariablebeingreferenced. autohotkeybyref Share Improvethisquestion Follow editedJun3,2014at0:20 bgmCoder askedMay30,2014at22:40 bgmCoderbgmCoder 6,07588goldbadges5555silverbadges103103bronzebadges 0 Addacomment | 2Answers 2 Sortedby: Resettodefault Highestscore(default) Trending(recentvotescountmore) Datemodified(newestfirst) Datecreated(oldestfirst) 2 ThisapprochusesthebuildinListLines-Commandtoaccesstheneededmetadata. ThecommandListLinesopensthemainwindowofthecurrentscriptanddisplaysthelastexecutedscriptlines. Contentlookslikethis: Scriptlinesmostrecentlyexecuted(oldestfirst).Press[F5]torefresh.Thesecondselapsedbetweenalineandtheoneafteritisinparenthesestotheright(ifnot0).Thebottommostline'selapsedtimeisthenumberofsecondssinceitexecuted. ----D:\Eigene_Dateien\ahkscripts\test3.ahk 002:myvar:="george" 003:passit(myvar) 007:MsgBox,GetOriginalVariableNameForSingleArgumentOfCurrentCall(A_ThisFunc) 012:lines:=ListLines() Press[F5]torefresh. Thisdatacanbeparsedtoextractthewantedinformation(whatispassedto'passit'). Oneproblemhereis,thatthereisnobuildinprogrammaticallywayofaccessthisinfo. ThefunctionListLinesoverridestemporaryUser32.ShowWindowandUser32.SetForgroundWindowtoreturnsimplytrue,sothebuildincommandListLinescanbeusedwithoutdisplayingitswindow(Mightproduceproblemswithmultithreadedscripts).Fromthis'hidden'windowitstextisreceivedandcleanedup.FunctioniswrittenbyLexikos(http://www.autohotkey.com/board/topic/20925-listvars/#entry156570http://www.autohotkey.com/board/topic/58110-printing-listlines-into-a-file/#entry365156). GetOriginalVariableNameForSingleArgumentOfCurrentCallextractsthevariablenamewitharegularexpression,whichsearchesthefirstcalltothepassedfunctionabovethecurrentcall(calltoGetOriginalVariableNameForSingleArgumentOfCurrentCall). myvar:="george" passit(myvar) return passit(whatvar){ msgbox%GetOriginalVariableNameForSingleArgumentOfCurrentCall(A_ThisFunc) } GetOriginalVariableNameForSingleArgumentOfCurrentCall(callerFuncName) { lines:=ListLines() pattern=O)%callerFuncName%\((.*?)\).*?%A_ThisFunc%\(.*?\) RegExMatch(lines,pattern,match) returnmatch[1] } ;OriginallywrittenbyLexikos/CopyofListGlobalVarshttp://www.autohotkey.com/board/topic/20925-listvars/#entry156570 ;withmodificationsfromherehttp://www.autohotkey.com/board/topic/58110-printing-listlines-into-a-file/#entry365156 ;Tested/ModifiedforAHKUnicode64bitv1.1.14.03 ListLines() { statichwndEdit,pSFW,pSW,bkpSFW,bkpSW ListLinesOff if!hwndEdit { dhw:=A_DetectHiddenWindows DetectHiddenWindows,On Process,Exist ControlGet,hwndEdit,Hwnd,,Edit1,ahk_classAutoHotkeyahk_pid%ErrorLevel% DetectHiddenWindows,%dhw% astr:=A_IsUnicode?"astr":"str" ptr:=A_PtrSize=8?"ptr":"uint" hmod:=DllCall("GetModuleHandle","str","user32.dll") pSFW:=DllCall("GetProcAddress",ptr,hmod,astr,"SetForegroundWindow") pSW:=DllCall("GetProcAddress",ptr,hmod,astr,"ShowWindow") DllCall("VirtualProtect",ptr,pSFW,ptr,8,"uint",0x40,"uint*",0) DllCall("VirtualProtect",ptr,pSW,ptr,8,"uint",0x40,"uint*",0) bkpSFW:=NumGet(pSFW+0,0,"int64") bkpSW:=NumGet(pSW+0,0,"int64") } if(A_PtrSize=8){ NumPut(0x0000C300000001B8,pSFW+0,0,"int64");returnTRUE NumPut(0x0000C300000001B8,pSW+0,0,"int64");returnTRUE }else{ NumPut(0x0004C200000001B8,pSFW+0,0,"int64");returnTRUE NumPut(0x0008C200000001B8,pSW+0,0,"int64");returnTRUE } ListLines NumPut(bkpSFW,pSFW+0,0,"int64") NumPut(bkpSW,pSW+0,0,"int64") ;RetrieveListLinestextandstripoutsomeunnecessarystuff: ControlGetText,ListLinesText,,ahk_id%hwndEdit% RegExMatch(ListLinesText,".*`r`n`r`n\K[\s\S]*(?=`r`n`r`n.*$)",ListLinesText) StringReplace,ListLinesText,ListLinesText,`r`n,`n,All ListLinesOn returnListLinesText;ThislineappearsinListLinesifwe'recalledmorethanonce. } Share Improvethisanswer Follow editedJun5,2014at9:07 answeredJun4,2014at16:41 hippibruderhippibruder 16844bronzebadges 3 Say,thatseemstowork.Thankyou!Thereisalotgoingonthere,canyouexplainwhatishappening?Justtomakeitevenmoreinteresting,Ididthis:globalmyvarmsgbox%GetOriginalVariableNameForSingleArgumentOfCurrentCall(A_ThisFunc)."=".myvartogetthemessageboxtosay:myvar=george – bgmCoder Jun4,2014at18:50 1 @BGMIhaveaddedexplanation – hippibruder Jun5,2014at9:09 Excellent!Thankyouverymuch-Iunderstandandthattomeisworthasmuchasthesnippet. – bgmCoder Jun5,2014at13:31 Addacomment | 1 Theclosesttowhatyouwouldwant...?ThisremindsofaquestionIhad. Seehttp://ahkscript.org/boards/viewtopic.php?f=14&t=3651 myvar:="test" passit("myvar");displayvalue,andchangeit msgbox%"myvar="myvar passit(byrefwhatvar){;nomoreneedforbyrefhere... msgbox%whatvar"="(%whatvar%) %whatvar%:="blah";editglobalvar"hack" } Share Improvethisanswer Follow answeredMay31,2014at18:31 JoeDFJoeDF 5,22066goldbadges3939silverbadges6262bronzebadges 4 JoeDF-thatisclose.ProblemisIwanttopassthevariableasavariable,notasastring.ThenIwantthefunctiontobeabletoknowthestringnameofthepassedvariable. – bgmCoder Jun2,2014at13:39 @BGMHmmIdon'tknowifit'spossible...Howarethevariablesactuallycreated? – JoeDF Jun2,2014at22:28 @BGMok,isee...ifitabsolutelycannotbepassedasastringthen,Ireallydon'tknowifit'spossible... – JoeDF Jun3,2014at1:39 Ithinkheneededthebyrefsothatpassitcouldmodifythespecifiedvariable.Iagreethatitwouldbeconvenientifthereweresomeconstructforgettingthenameofavariableasastring,butthat’sfortheWishListsectionoftheforum…ifithasn’talreadybeensuggested—Ican’tdetermineifithasornot. – Synetech Apr9,2016at0:26 Addacomment | YourAnswer ThanksforcontributingananswertoStackOverflow!Pleasebesuretoanswerthequestion.Providedetailsandshareyourresearch!Butavoid…Askingforhelp,clarification,orrespondingtootheranswers.Makingstatementsbasedonopinion;backthemupwithreferencesorpersonalexperience.Tolearnmore,seeourtipsonwritinggreatanswers. Draftsaved Draftdiscarded Signuporlogin SignupusingGoogle SignupusingFacebook SignupusingEmailandPassword Submit Postasaguest Name Email Required,butnevershown PostYourAnswer Discard Byclicking“PostYourAnswer”,youagreetoourtermsofservice,privacypolicyandcookiepolicy Nottheansweryou'relookingfor?Browseotherquestionstaggedautohotkeybyreforaskyourownquestion. TheOverflowBlog WhyAIishavinganon-premmoment(Ep.476) Opensourceandaccidentalinnovation FeaturedonMeta Recentsiteinstability,majoroutages–July/August2022 PleasewelcomeValuedAssociate#1301-Emerson The[maintenance]tagisbeingburninated StagingGroundWorkflow:QuestionLifecycle Whatshouldwedowithimproperlycitedposts? Related 1 PassinginvariablesByRefinActionscript3 4 SwitchingByreftoByvalonmethodcallsVB.NET 28 Understandingbyref,refand& 1 WhyisitalwaysByRefwhenIspecifybyByVal? 2 VB.NET-FunctionCannotModifyaMemberOfAnArray 1 HowamIabletoextractthevalueofavariablestoredinsideanothervariable? 3 VBAByRefargumenttypemismatch 1 C++TemplatesByRefvs.ByVal 1 ByRefArgumenttypemismatchwhenpassinganarraytoasuborfunction 0 AHKcodeissue-ImportinganddefiningvariablesinAHK? HotNetworkQuestions Galatians4:14.PaulsaysthatJesusisAngeloftheLord? CarrypassportwhiletravellinginSchengenarea Thegrammarof死ぬ死ぬ言わないの Dononconstructiveproofsofisomorphismexist? Buttonsthatdonotbounceorscopesthatpretendtobe100MHzbutactuallyaren't? HowdoChristiansrespondtothecriticismthatJesusofNazarethdidnotbringworldpeace? Doplanetsloseenergywhilerotating? Carry-lesssumgivenabaseb WhatisthelowerlimitofNiCdcellvoltage? Oldscifibook:detective,alienconspiracy,changeappearancemachine,hugebraininspaceship,aliencommunicatesbyflashinglightsfromstomach CanIapplyfortouristvisawhilelivinginadifferentcountryasanexpat? WhydoeseveryoneinTheLordoftheRingsuse"vous"? Buildyourownpuzzle! Drawingabondingcurve Whataretheeffectsofmakingawomanaslightasaduck? Analgorithmtofindevensublimenumbers Isitsafetodrillacableexitholeinaseatpost? Whatis"iceorange"andwhatdoesithavetodowithhorses? Whatisthiselectricalcomponentcalled? Stream.peek()canbeskippedforoptimization Avoidbreakingwordsbeforeorafterasterisk('*') StrangecharactersappearinginsomeDNScheckers,butnotothersforDKIMandSPF,possiblycausingDMARCtofail InwhatWesternCountrieshasanypartyorcoalitionbeenelectedgainingasupermajorityorsuchmajoritypermittingconstitutionalamendments? Areairshipspracticalinaworldwithoutmuchmetal? morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings
延伸文章資訊
- 1AutoHotkey-Scripts/Functions.ahk at master - GitHub
A collection of my AutoHotkey scripts and libraries - AutoHotkey-Scripts/Functions.ahk at master ...
- 2returning values from an AutoHotkey function with byref
- 3what does ByRef do? - AutoHotkey Community
You can compare a byrefparameter to the 'outpuvar...' paramater of MouseGetPos command, for exemp...
- 4函數- AutoHotKey.tw - Google Sites
同樣地, 使用ByRef 送回長字串給呼叫者通常比類似 Return HugeString 的方式執行的更好. [AHK_L 60+]: 如果傳遞給ByRef 參數的不是可修改的變數, 那麼函數...
- 5Return multiple values from AutoHotkey functions with byRef
In my initial video I talked through how & why to use AutoHotkey functions as well as how to retu...