十二 312010
 

转自http://linux.byexamples.com/archives/406/how-to-embed-lua-51-in-c/

今天编译的时候出错了,百度了一下只有这一个结果

自己留着,以后用得着

 

How to embed Lua 5.1 in C++

Lua
Lua, is a scripting language providing dynamic data structures, maths, io and string manipulations just like any interprete language such as Bash, Python, Ruby etc.

What is so special about Lua?
Lua is Fast, Light-weight and Embeddable.

Lua can be embedded into c and c++ programs and Lua core are statically complied with your c++ programs, meaning your c++ program itself are now becoming Lua interpreter that execute Lua scripts. To extend your c++ application to execute Lua script is simple, lets check it out.
Before you start, please download and install Lua from HERE.
Disclaimer: My example are based on Lua 5.1.3.

1. Create a simple Lua script and name it as foo.lua.

io.write("Please enter your name: ") name = io.read() -- read input from user print ("Hi " .. name .. ", enjoy hacking with Lua");

2. Write a cpp program clua.cpp to execute foo.lua.

extern "C" { #include "lua.h" #include "lualib.h" #include "lauxlib.h" } int main() { int s=0; lua_State *L = lua_open(); // load the libs luaL_openlibs(L); //run a Lua scrip here luaL_dofile(L,"foo.lua"); printf("\nI am done with Lua in C++.\n"); lua_close(L); return 0; }

Lua API are in c format, in order to make it work with C++ you need to extern “C”. luaL_openlibs(L) loading up all the basic libs such as IO, String, Math etc. I believe if you are using Lua 5.0, you have to replace luaL_open(L) to load the libs one by one like this:

 luaopen_base(L); luaopen_table(L); luaopen_io(L); luaopen_string(L); luaopen_math(L);

3. Compile the clua.cpp with g++.

g++ -o clua{,.cpp} -llua -ldl

IMPORTANT! You need to link you program with libdl besides liblua. I believe the use of luaL_openlibs() are calling dlopen, dlclose, dlerror, dlsym which needs libdl.

Else you may get linking error like this:

/usr/local/lib/liblua.a(loadlib.o): In function `ll_loadfunc': loadlib.c:(.text+0x917): undefined reference to `dlsym' loadlib.c:(.text+0x924): undefined reference to `dlerror' loadlib.c:(.text+0x9fc): undefined reference to `dlopen' loadlib.c:(.text+0xa11): undefined reference to `dlerror' /usr/local/lib/liblua.a(loadlib.o): In function `gctm': loadlib.c:(.text+0x101e): undefined reference to `dlclose' collect2: ld returned 1 exit status 

4. Execute your c++ app

$ ./clua Please enter your name: surface Hi surface, enjoy hacking with Lua I am done with Lua in C++. 

Cool isn’t it?

Lets try to change foo.lua into this:

io.write("Please enter your name: ") name = io.read() io.write("Hi " .. string.format("\27\91\1;38;40m%s\27\91\0;47;40m",name) .. ", enjoy hacking with Lua\n");

Now, run ./clua again! You name will be in RED, check out text color example HERE

Ofcause, in order to really extend your c++ apps to Lua script, you need more than lua_dofile(), you need to allow Lua script calling your c++ functions, you may need to access variables from Lua to c++ and vice versa. Well, mean while I am still learning, I will share more when I learn more tricks!

Reference and Tutorial!
Lua provides excellent documentation:


  58 Responses to “linux c代码调用lua的一些注意事项”

  1. Whereabouts are you from?

  2. Appreciation for this infromiaotn is over 9000-thank you!

  3. It is very individual. For me ciilas works best. I have tried viagra and ciilas so far. Viagra gave me a headache sometimes and sometimes a weird feeling the next morning (hard to explain what exactly) ciilas has no side effects for me so far, altough I think that the erections viagra gave me were somehow more intense.I think the doc knows what he’s doing so you should trust him.Also this is a good source of info viagrausers.infoit is an online community of viagra ciilas and levitra users. the site also has got a good message board and price comparison of cheapest trusted online pharmacies for all 3 viagra ciilas levitra.He could ask some guys on the forums there, they are experienced with these ed meds

  4. / Thanks for your write-up. I would also like to remark that the very first thing you will need to cnucodt is to see if you really need credit restoration. To do that you need to get your hands on a duplicate of your credit history. That should never be difficult, because government mandates that you are allowed to have one cost-free copy of the credit report on a yearly basis. You just have to inquire the right men and women. You can either browse the website owned by the Federal Trade Commission or even contact one of the leading credit agencies instantly.

  5. Can some one please exialpn in detail how the maternity drop out effects the CPP calculation. Also how the CPP is calculated based on your credits. The statements are available of course, but they fail to describe how the estimates are arrived at. Detail needed.Also if the drop out is 15% from your contribution period and your contribution period is the age when you take the pension this results in a different calculation, particularly if you stop working years before age 60.

    • Retiring these days is unluckily haderr and haderr with more costly medical insurance and the risk that social security will not survive or be severely watered down. Saving money is very important to prepare our retirement which will really comes to every employee.

    • that, permit me iofnrm you precisely what did do the job. The authoring is certainly highly convincing and this is probably the reason why I am taking an effort in order to opine. I do not make it a regular habit of doing that. Second, while I can easily notice a jumps in reasoning you come up with, I am not really convinced of how you appear to connect the points which produce your final result. For right now I will, no doubt subscribe to your point but wish in the near future you link your dots better.

  6. Ruby,The current rules state that somnoee under 65 would need to stop working or have reduced income. For 65 and over, even under these current rules you could collect CPP while still working. Keep in mind that the longer you can go without it, between 65-70, the more they would pay you once you do start. If you’re still working, you might be able to hold off. However, if you have any debt that you’d like to pay off now then it might work out better to start receiving your CPP and applying this amount against it.

    • Stock: Those concerned with prnetctiog people who choose not to protect themselves prefer that there be no opt-out. I’m on the fence.@Big Cajun Man: The way I think of it is that CPP benefits for a given individual should be based on how much he or she paid into the CPP system. So, if you paid into CPP under the old rules for 35 years and under the new rules (with higher CPP contributions) for 5 years, you’d get a blended amount of CPP benefits when you retire. You’d get a little more than you would have under the old rules, but not much.

    • Hi there just wanted to give you a quick heads up. The text in your cennott seem to be running off the screen in Ie. I’m not sure if this is a formatting issue or something to do with web browser compatibility but I figured I’d post to let you know. The layout look great though! Hope you get the problem solved soon. Kudos

  7. - hmm a camera that has more than just the shetutr, zoom, play, delete buttons and the arrow keys. e.g. if your camera has P, A, S, M mode selection dial, allows you to select the point of focus, etc. Most semi decent compacts days usually have some of those features that allow you some sort of manual controls or override.

  8. alekiel – way to go Auey!!! i’m soooo proud of you! you’re an amazing peatogrophhr and now you have the paper to prove it. hehehe. take care and see you soon my friend. mwah!!!

    • This is great! I also agree that sometimes pelope are hesitant when it comes to the idea of a financial advisor and I believe a Money Mentor is a great alternative. If pelope have some outside opinion when it comes to making personal finance decisions it may result in a different outcome. Who knows, it may even help pelope avoid bankruptcy!

    • Seems to me all these rules are a little on the spitud side given they take a top down approach! Simple rule add up your expenses over a year! Make sure you can cover them for the expected life expectancy of a man or woman ignore CPP and OAS they become a bonus ie covering extras new car new roof vacation etc! I call it the rule of common sense!

  9. PTK,That is quite a machine. I’ve never tried teal/truss on dual petuinm set-ups. Shouldn’t be a problem and actually kinda coolI apologize for the problems you have run into. Regarding the make alias, we should def fix that.It seems like you’re up and running?Out of curiosity, what simulator and what version do you use? I’m currently running on a quite old VCS, and we haven’t been paying attention to versions of verilog simulators

    • The rule of 20 and the 4% rule have been with us for ages. Neither address the true cpiolexmties for most individuals. For instance, are your savings inside your RRSP or outside (non-reg/TFSA)? Pension? Do you have a loan you are paying off? Will you take early or late CPP?, do you anticipate a future windfall (selling the cottage, downsizing, inheritance) and the most important aspect of all:- income tax and it’s effect on the different forms of capital (reg/nonreg/equity/tfsa) as they come in and out of play over time.Remember, you don’t need a financial advisor to do this you have a better handle on this knowledge base. It’s called financial planning, and everyone should be doing it on their own. Financial advisers will direct you as to what’ kind of investments to choose the financial plan tells you the how much’ and when’ (the scale and timing)In summary: Financial plan, DIY. Investment plan, your advisor.

  10. I am getting a supuiors error in the mutex_test:Sometimes it’s like this:[81 ps][top][simple thread 7 on transactor 1][FILE: ./mutex_test.cpp][line: 175][ERROR] of 20 bins 17 were within two standard deviations. Expected at least: 19But it seems the number of bins varies:[81 ps][top][simple thread 5 on transactor 1][FILE: ./mutex_test.cpp][line: 175][ERROR] of 33 bins 30 were within two standard deviations. Expected at least: 31.35And sometimes there is no error. So there are two problems to debug here, the supuiors error message, and the lock up. Is this a real error, or just a did not get the bus in time error (but nevertheless, got the bus eventually)?

  11. Hi again,After trying direffent number of threads and iterations, I see this message in the log:[1 ps][Teal::synch][verification_top][FILE: ./teal_synch.cpp][line: 165][INFO]Thread : Teal Control Thread (0x489fbb0) is waiting.I guess it can’t be good that the control thread is waiting as it would not be able to dispatch the other threads.I don’t quite understand why some messages are printed sometimes, and some other times they are not printed. I seem to get this changing behavior simply by changing the number of iterations or number of threads.PS: I don’t know which reply button to hit anymore on this forum sorry if I hit the wrong one. I find phpbb forums easier to read than drupal’s, but this is just personal preference.

  12. Short, sweet, to the point, FREE-extacly as information should be!

    • I’m not sure I understand your cutialalcon. Did you assume the person’s investment portfolio started at $0 at retirement and then all CPP proceeds were invested? That seems a rather artificial situation, but perhaps it is representative after all for those people who don’t really need their CPP to pay their expenses.Many real retirees probably have most of their net worth in their homes (real estate), meaning their real investment returns would be around 0%. However, I suspect 0% would not be the right number to plug into your chart — would it be better to plug in the expected returns for the actual CPP proceeds being invested?

    • Can you please tell me what your rate are for tainkg pictures of 6 newborn puppies? We would probably wait until they are about 4 weeks and have their eyes open.Thanks

  13. Hi Jim,Great post. I really like the money metonr concept. I think a lot of people are often a bit reluctant to go the DIY route, but at the same time know they are not getting the best bang for their buck by having a financial advisor who is possibly charging and taking’ (for lack of a better word) a chunk of their hard-earned dollars.Personal finance is just that, it’s personal’ to a lot of people, and I think seeking out a money metonr could be the best route for many people.I think you just described your new title [If I'm not mistaken, you spent over a decade as an investment advisor, correct?]All the best,TWC

  14. Viagra and Levitra have the same generic names silaendfil’.The active ingredient of Cialis is Tadalafil.About the efficacy, better check with your doctor, especially you are taking some other medications and with concurrent disease as

  15. How many Canadians Does it Take To Support an Aging, Entitled Baby Boomer? Back when the Canada Pension Plan was founded (1966) and when unirsveal healthcare was adopted (1996/1984) there was 6.8 workers for every 1 retired person. In 1966 the CPP cost Canadian workers 1.8% of their gross pay. Fast forward to 2010 there are 4.5 workers per 1 retired person with 10,000 Baby Boomers turning 65 every day for the next 18 years. That is 416 per hour, 7 every minute. In 2010 the CPP currently takes a 9.9% premuium to fund itself from every worker in Canada. (5.495% from the employee and 5.495% from the employer). This represents a whopping 450% increase in CPP premiums as the worker/retiree ratio shrank by 34%. So for every 1% drop in the worker/retiree ratio, CPP premiums have gone up by 13%.Now contemplate the year 2030 in that year there will be 2.5 workers per 1 retired person. Why 2030? That is the year the last Baby Boomer will turn 65. That 2.5 worker/retiree ratio will 44% lower than it was in 2010 and 70% lower than it was in 1966. So if the CPP premiums only go up at the same ratio as they have increased to date that will mean every Canadian worker can expect to pay a CPP premium of 57%. Split with your employer paying 28% and you paying 28% please remember that that 57% tax on your gross pay hasn’t yet funded a single dollar of the gun registry, paid for a single MRI in your local hospital or trained a single new worker to replace you when and if as a member of the post-BabyBoom generation you ever hope to retire.Now you are supposed to be comforted by the fact that the Baby Boom generation is saving and investing more than any previous generation and hence the need for the CPP will reduce over time. The generations that survived the Great Depression and WWII didn’t really have time or money enough to save for retirement, hence the need for the CPP in the first place. Do you really think Canada’s employers will stand for paying a 28% payroll tax to fund retirees? No i predict this will be the next big movement in the politics of pensions watch as the Canadian Federation of Indepent Business, the Chambers of Commerce, etc,etc, increasingly pour money into lobbying the federal government to cap their rate where it is (4.95%) and shift any increase in CPP deductions solely onto employees. Don’t believe me? Check out the chart of worker to retiree ratios in today’s GlobeandMail.Don’t trust my CPP rate calcuations? Visit the very good wikipedia article on the CPP here.Think there can’t be THAT many baby boomers? Here are the numbers. draft tell me where my numbers are off please. for some reason i have found myself blogging about the CPP lately

  16. Admiring the hard work you put into your website and in depth infiomatorn you provide. It’s good to come across a blog every once in a while that isn’t the same unwanted rehashed material. Wonderful read! I’ve bookmarked your site and I’m adding your RSS feeds to my Google account.

  17. Having problem with our skin can give us derespsion, yes it is due to the anxiety that we feel when we see other people staring at you and looking in your dry loose aging skin! Many people specially women who are experiencing this kind of scenario, but don’t worry there are many machine and procedures that can help us to stay away from this stage of our lives. Thanks to technology, for providing us high quality gadgets to improve our appearance and to gain confidence.

  18. Cialis is the new wonder drug that can last up to 36 hours..No, not the etroeicn just the medication..So when the time is right he’ll be ready and can perform several times during that 36 hours..Viagra is the first one to hit the market and must be taken at least an hour before and doesn’t always stick around for a second showing..Levitra is pretty much the same as Viagra..All of these drugs come with great risks if you have or have had heart problems or are a diabetic..Men also run the risk of having an etroeicn that lasts longer than 3-4 hours and must be taken to the emergency room for medication injections to remedy the situation Everyone is different and the drugs work differently for each person..See a Urologist who can prescribe the best drug for him..

  19. From your comment on the FWP cotmnems: > I would rather not display this stuff, of course, so I may end up going with the delicious option, however, ideally I would like to use GR and if there’s some way to truncate the entry, perhaps by the number of characters? Could that be easily added as an option?My response:You can truncate the display of posts in your template so that the full content doesn’t show, or else you could use the filter the_content’ in a plugin and truncate the content there after checking if the post being displayed was aggregated or not (if you know php). You could also apply it to rss using the filter the_content_rss’ (though i don’t even think you’d have to, the_content affects both AFAIK). That’s what I did for the aggregated content on the site i use FWP on.

  20. Angel, every patient sluohd speak directly with their local doctor before beginning any new medication, especially if they have high blood pressure or other conditions. Thanks for your question. Viamedic Admin

  21. I thank every one, born after 1939 especially those in power who deiecdd everyone has a right to home ownership and pressured banks to make bad loans. Also those who deiecdd job loss over the last 50 years was OK. .Short List

  22. Hey! I know this is kinda off topic however , I’d fugerid I’d ask. Would you be interested in trading links or maybe guest writing a blog post or vice-versa? My blog covers a lot of the same subjects as yours and I believe we could greatly benefit from each other. If you are interested feel free to shoot me an e-mail. I look forward to hearing from you! Terrific blog by the way!

  23. Cajun Man: I’m no expert on pulbic pensions, but I thought that the pension reduction was a calculation designed to take into account the value of CPP but that it isn’t exactly equal to your CPP payments. I don’t know if it factors in the actual age you start drawing CPP. If it does not, then my analysis still applies.Infinity is just above age 95 — it means that you shouldn’t start your CPP until age 70 :-)

  24. With interest rates so low, and expcteed to rise, bonds and annuities are out; the stock market is risky except, perhaps in the very long term; real estate is high and falling in most areas; cash loses to inflation I’m getting .88% in my premium money market fund; precious metals are subject to gut-wrenching fluctuations and are really more of a store of wealth than an investment; and government programs will be subject to erosion by inflation and clawbacks. I think this is a hard time to be planning for retirement; I’m pretty sure it’s not just my imagination.

  25. Great cmmoon sense here. Wish I’d thought of that.

  26. If you never or seldom paid in to the Social Security seystm you will not be qualified for benefits, just like any other retirement plan. Most Baby Boomers are fine, they get their money and benefits. Only people that are spouses or dependents of a member, can legally get any benefits as well. Social Security was never meant to be an insurance program for ALL Americans, you have to contribute.Homeless? I suspect a few might. But the great majority of Baby Boomers are fine. And don’t worry about the government, they cant take anything away from you.Yes, it is the younger generations that needs to be thinking of their future. The government is gonna be getting out of annuity/insurance business. They would much rather see folks run their own retirement programs. Besides that, it is better for the economy that investments be made in the private sector.Most the Baby Boomers did just that, they have Social Security but they also have investments and annuities. It is gonna be rough on people that have to live just off Social Security and even worse for those that have nothing set aside for old age. They will become a burden to society.

  27. viagra is strong takes loegnr to have an effect about an hour and it doesn’t go away for up to 4 hours. it can make you go blind if you are sinsitive to it you’ll see blue spots then your vision goes bye bye cialis is not as strong as viagra but works faster usually in 30 minutes and goes away in 2 hours or less it can also make you go blind but its not as common as it is in viagrai don’t know anything about levitria

  28. Hi Leanne, I came across the same pbrelom you did, and unfortunately found no solution. This is why it took a couple of months to transfer, because I literally had to cut and paste every entry and comment from BC to WordPress. I had almost 400 entries and probably 3 times that many comments, so it was pretty horrible. Hopefully your person doesn’t have quite this amount. I did find someone who supposedly created (or had someone create) a script to do this, but when I emailed her, I got no response Levi

  29. Wow! What kind of person would atuaclly provide any market support to a vendor who tries to get business by spamming people with fraudulent invitations? A moron? A completely unprincipled idiot? Ah, well…I suppose there is a certain natural justice in it. They (vendor and buyer) certainly deserve each other.

  30. bunch of bullshit from bux96 and bux69so you like to cloampin about war? MOVE YOUR? BODY AND DO A LEGAL PROTEST!!! there’s no perfect government or country in this planet [and who thinks that lives in one, is too retarded to understand all].or a better option, write a book about your sickness and sell it

  31. Stands back from the kbeyoard in amazement! Thanks!

  32. That’s a state by state decision. In some stteas, if one person is over the age of concent, and the other is under, but only by a gap of two years between the couples, it’s legal. (Montana law, 16 years for age of concent, but no legal implications if they are within two years of each other(So I’d look up your state laws

  33. Unless they have recently ceghand the requirements, it should not be a problem providing that she meets the eligibility required for her working visa. Different employers may require certain certifications, but with her experience, she sounds like she is very qualified. I’ve looked into it as I was considering moving there to teach as well. I wish her the best!As far as I know, New Zealand does not require a certificate unless they recently ceghand their requirementsReferences : Yoga teacher

  34. Loser..como analista poledtico es tan bueno como la loba y sus lobtois republicanos pate9ticos, los que este1n apretando a los pobres en este paeds son los republicanos y quienes se van a ver afectados en las elecciones son ellos, ya que los republicanos este1n queriendo que el gobierno cierre sus puertas y cancele muchos programas que ayudan a los nif1os, mujeres y ancianos .

  35. my husband is in his 50 s and takes cilias whenever he feels he needs it which is usually based on his stress levelit has proven to be a wonderful drug and he has had no side effects, but he does cut the pill and half and only take a half at a timehope this info helpsMJ

  36. I’d go one generation back. The Greatest Generation faeild us. When they were raising the Baby Boomers they spoiled and indulged them not wanting them to face the same hardships they did while growing up, but they faeild to see that those hardships built character which enabled them to endure the tougher times. They won the war against fascism but lost the war at home.

  37. Angel, every patient sholud speak directly with their local doctor before beginning any new medication, especially if they have high blood pressure or other conditions. Thanks for your question. Viamedic Admin

  38. Thanks Jeremy, I had to think for a bit what your comment was about. I’ve plaid with the pgliun (feed WordPress) a bit on a test implementation on another site, but I’ve been too busy to do much (or write much as you see here!) for a couple of months! Gonna try to change that, so thanks, I’ll refer to your comment again when I start looking at this, hopefully soonish Levi

  39. David, you do not need a prescription in hand. One of our U.S.-licensed dotcros may write you a prescription after they review the medical/health questionnaire that you fill out online. Thanks.

  40. Should definitely give your local phmaracy a call, and ask for a consultation with their pharmacist. Levitra is a regularly prescribed medication. A pharmacist would be able to give you the various pros/cons, interactions and general effect of the med. CVScustomers.com

  41. La gente como Yo, estamos a punto de vivir bajo los puteens porque el dinero no nos alcanza ni para pagar la renta, estamos comiendo en los comedores, haciendo colita para colectar la latica que nos este1n dando para poder llevar a nuestro hogar y poder hecharle algo a nuestro estomago . Dr, Claudio Loser, cual es su analice sobre estas declaraciones.? estas escena es en la Florida, bastif3n de los republicanos..esa es la miseria que seguire1 exportando al mundo.?

  42. El Dr. Claudio Loser es Socio Fundador ased como Presidente y Director Ejecutivo (CEO) de GCLA. Es tambie9n Senior Fellow del Die1logo Interamericano, un foro para ledderes de opinif3n pfablica y formulacif3n de poledticas para el Hemisferio Occidental. El Dr. Loser es un rcoenocido experto en las economedas de Ame9rica Latina y el Caribe. De 1994 a 2002, fue Director para el Departamento del Hemisferio Occidental del Fondo Monetario Internacional.

  43. I have also grown up with golden rerertveis and your photography shows their personalities so well! The backdrops, props, babies, and animals are perfect! I was linked to your website through gbgrr.org and I am so glad I explored!I may have to bring Smudge (My four year old goofball golden) to you one day!

  44. Keep track of what you are spending and eianrng by opening a separate account for your business. Get in the habit of sending everything to this account. This way, you have a detailed record of all money that flows through your business. Also consider getting a credit card to use specifically for business transactions, like ordering supplies.

  45. No, it is not legal in CA. Not only that, it is not safe! You really need to riehtnk the situation and try to get some support from others. There are a lot of people out here who want to help you to make the most of your life. Also, consider this, do you really want to see him go to jail if he is found out? Join PURE Discipleship Program and get a mentor to help you.

  46. Jack, are you kidding? I am a Baby Boomer. I did notinhg but worked my entire life from age 13 and until today. Everyone I know and respect ( that is, in my age range), is pretty much like me.I see 70 years of raising shitlamic imperialist thrust, using liberal movements all over the world, being really guilty in pushing America The Great towards self-destruction for shitlamic delight. Especially under fuhrer hussein obama. So how am I responsible for the sins you’ve outlined?

  47. ss and medicare wont cease for us bomoers we are too old now , however the younger work force better save their money cause it wont be there for them. ss was started partly to get the older worker off his job so a younger worker could have it , and like every government program it grew out of control , myself i paid ss taxes since 1967 to 1995 , when i had to take a medical retirement im 60 now and have been drawing ssa since i was 45

  48. Howdy, i read your blog from time to time and i own a similar one and i was just couuirs if you get a lot of spam remarks? If so how do you protect against it, any plugin or anything you can recommend? I get so much lately it’s driving me mad so any support is very much appreciated.

 Leave a Reply

(required)

(required)


− 1 = 8

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>